用Java标准的ServerSocket写一个简单的服务器,该服务器绑定本地端口80等待客户端连接,服务器收到客户端Socket连接后只简单的发一个“hello,world”后就断开连接。
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class JavaServer {
public JavaServer() throws Exception {
ServerSocket serverSocket = new ServerSocket(80);
while (true) {
Socket socket = serverSocket.accept();
System.out.println("接受连接");
OutputStream oStream = socket.getOutputStream();
oStream.write("hello,world!".getBytes());
oStream.close();
socket.close();
System.out.println("数据发送完毕");
}
}
public static void main(String[] args) {
try {
new JavaServer();
} catch (Exception e) {
e.printStackTrace();
}
}
}
现在开始用netty写一个客户端,该客户端对服务器端发起连接,连接成功后把收到的数据用标准Java的Logger打印出来:
import java.net.InetSocketAddress;
import java.util.logging.Logger;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
public class Client {
public Client() throws Exception {
String host = "127.0.0.1";
int port = 80;
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class).remoteAddress(new InetSocketAddress(host, port))
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new MyClientHandler());
}
});
ChannelFuture f = b.connect().sync();
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully().sync();
}
}
private class MyClientHandler extends ChannelInboundHandlerAdapter {
private final Logger logger = Logger.getLogger(MyClientHandler.class.getName());
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf in = (ByteBuf) msg;
logger.info(in.toString(CharsetUtil.UTF_8));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // 4
cause.printStackTrace();
ctx.close();
}
}
public static void main(String[] args) {
try {
new Client();
} catch (Exception e) {
e.printStackTrace();
}
}
}
收到数据:
zhangphil.server.Client$MyClientHandler channelRead
信息: hello,world!