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

2 篇文章 0 订阅

现在用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();
		}
	}
}

 

服务器端输出:

 

客户端输出:

 

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhangphil

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值