netty的tcp服務端

jar包下載,http://pan.baidu.com/s/1hr2VBzY
import org.apache.log4j.Logger;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;


public class NettyServerBootstrap {


private static Logger logger = Logger.getLogger(NettyServerBootstrap.class);


private int port;


public NettyServerBootstrap(int port) {
this.port = port;
bind();
}


private void bind() {


EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup worker = new NioEventLoopGroup();


try {


ServerBootstrap bootstrap = new ServerBootstrap();


bootstrap.group(boss, worker);
bootstrap.channel(NioServerSocketChannel.class);
bootstrap.option(ChannelOption.SO_BACKLOG, 1024); //連接數
bootstrap.option(ChannelOption.TCP_NODELAY, true);  //不延遲,消息立即發送
bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); //長連接
bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel)
throws Exception {
ChannelPipeline p = socketChannel.pipeline();
p.addLast(new NettyServerHandler());
}
});
ChannelFuture f = bootstrap.bind(port).sync();
if (f.isSuccess()) {
logger.debug("啓動Netty服務成功,端口號:" + this.port);
System.out.println("啓動Netty服務成功,端口號:" + this.port);
}
// 關閉連接
f.channel().closeFuture().sync();


} catch (Exception e) {
logger.error("啓動Netty服務異常,異常信息:" + e.getMessage());
System.out.println("啓動Netty服務異常,異常信息:" + e.getMessage());
e.printStackTrace();
} finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}


public static void main(String[] args) throws InterruptedException {

NettyServerBootstrap server= new NettyServerBootstrap(9999);


}


}


//具體實現



import java.io.UnsupportedEncodingException;


import com.sun.xml.internal.fastinfoset.stax.events.Util;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;


public class NettyServerHandler extends ChannelHandlerAdapter {


@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {

ByteBuf buf = (ByteBuf) msg;

String recieved = getMessage(buf);
System.out.println("服務器接收到消息:" + recieved);
int i=0;
if(!Util.isEmptyString(recieved)&&i<2){
try {
ctx.writeAndFlush(getSendByteBuf("APPLE"));
i++;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/*try {
ctx.writeAndFlush(getSendByteBuf("APPLE"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}*/
}


/*
* 從ByteBuf中獲取信息 使用UTF-8編碼返回
*/
private String getMessage(ByteBuf buf) {


byte[] con = new byte[buf.readableBytes()];
buf.readBytes(con);
try {
return new String(con,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}

private ByteBuf getSendByteBuf(String message)
throws UnsupportedEncodingException {


byte[] req = message.getBytes("UTF-8");
ByteBuf pingMessage = Unpooled.buffer();
pingMessage.writeBytes(req);


return pingMessage;
}
}

netty先啓動服務端,然後在啓動客戶端進行數據交互,這裏囉嗦一下

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章