Netty作为服务器和普通Java Socket客户端传输数据

现在用Netty写一个服务器Server,服务器端绑定本地端口80等待连接,当有客户端Socket连接过来后,就发送字符串“hello,world!”给客户端。客户端连接服务器,连接成功则读取字符串并打印出来,然后关闭socket连接。

服务器:

package zhangphil.server;

import java.util.logging.Level;
import java.util.logging.Logger;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class Server {
	private final int port = 80;

	public Server() throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();

		ServerBootstrap b = new ServerBootstrap();
		b.group(bossGroup, workerGroup).option(ChannelOption.SO_KEEPALIVE, true).channel(NioServerSocketChannel.class)
				.option(ChannelOption.SO_BACKLOG, 128).handler(new LoggingHandler(LogLevel.INFO))
				.childHandler(new ChannelInitializer<SocketChannel>() {
					@Override
					public void initChannel(SocketChannel sc) throws Exception {
						sc.pipeline().addLast(new StringEncoder());// 发送字符串的编码器。
						sc.pipeline().addLast(new StringDecoder());// 接收到字符串的解码器。
						sc.pipeline().addLast(new MyServerHandler());
					}
				});

		// 绑定端口,开始接收进来的连接。
		ChannelFuture cf = b.bind(port).sync();

		// 等待服务器关闭Socket。
		cf.channel().closeFuture().sync();
	}

	public class MyServerHandler extends ChannelInboundHandlerAdapter {

		private final Logger logger = Logger.getLogger(MyServerHandler.class.getName());

		@Override
		public void channelActive(ChannelHandlerContext ctx) throws Exception {
			System.out.println("连接激活");
			ctx.writeAndFlush("hello,world!"); // 若没有StringEncoder,则发送不出去字符串。
			System.out.println("写入完成");
		}

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

		}

		@Override
		public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

		}

		@Override
		public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
			logger.log(Level.WARNING, "发生错误,关闭链接。", cause);
			ctx.close();
		}
	}

	public static void main(String[] args) {
		try {
			new Server();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

客户端用普通Java的Socket实现:

import java.io.BufferedInputStream;
import java.net.Socket;

public class Client {
	public Client() throws Exception {
		Socket socket = new Socket("localhost", 80);

		BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());

		byte[] buf = new byte[256];

		System.out.println("开始读数据...");
		int count = bis.read(buf);
		System.out.println("读取数据数量:" + count);
		System.out.println(new String(buf));

		bis.close();
		socket.close();
	}

	public static void main(String[] args) {
		try {
			new Client();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

服务器端输出:

 

客户端输出:

 

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页