一、Socket简单通信

1、先启动server端

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**  
* @Title: tcpServer.java   
* @Description: TODO  
* @author pcm  
* @date 2018年6月8日 下午3:31:51
* @version V1.0  
*/
public class TcpServer {
	public static void main(String[] args) throws IOException {
		System.out.println("tcp协议服务器端启动");
		ServerSocket serverSocket = new ServerSocket(8080);
		//接收客户端请求
		Socket accept = serverSocket.accept();
		InputStream inputStream = accept.getInputStream();
		//将字节流转换成String类型
		byte[] bytes =new byte[1024];
		int len =inputStream.read(bytes);
		String result =new String(bytes, 0,len);
		System.out.println("服务器端接收客户端内容:"+result);
		serverSocket.close();
	}

}

2、启动客户端

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**  
* @Title: tcpServer.java   
* @Description: TODO  
* @author pcm  
* @date 2018年6月8日 下午3:31:51
* @version V1.0  
*/
public class TcpClient {
	public static void main(String[] args) throws IOException {
		System.out.println("tcp协议客户端启动");

		// 创建socket客户端
		Socket socket = new Socket("127.0.0.1", 8080);
		OutputStream outputStream = socket.getOutputStream();
		outputStream.write("我是客户端".getBytes());
		socket.close();
	}

}

使用线程池支持访问

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**  
* @Title: tcpServer.java   
* @Description: TODO  
* @author pcm  
* @date 2018年6月8日 下午3:31:51
* @version V1.0  
*/
public class TcpServer {
	public static void main(String[] args) throws IOException {
		System.out.println("tcp协议服务器端启动");
		ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
		// 创建服务端接口
		ServerSocket serverSocket = new ServerSocket(8080);
		try {
			while (true) {
				// 接收客户端请求
				final Socket accept = serverSocket.accept();
				newCachedThreadPool.execute(new Runnable() {
					public void run() {
						try {
							InputStream inputStream = accept.getInputStream();
							// 将字节流转换成String类型
							byte[] bytes = new byte[1024];
							int len = inputStream.read(bytes);
							String result = new String(bytes, 0, len);
							System.out.println("服务器端接收客户端内容:" + result);
							OutputStream outputStream = accept.getOutputStream();
							outputStream.write("服务端接收到请求了".getBytes());
						} catch (IOException e) {
							// TODO Auto-generated catch block
						}
					}
				});

			}
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			serverSocket.close();
		}
	}
}



二、使用netty3通信

1.netty3服务端

/**  
* @Title: NettyServer.java   
* @Description: TODO  
* @author pcm  
* @date 2018年6月11日 下午3:27:24
* @version V1.0  
*/
// Netty 服务器端
public class NettyServer {
	public static void main(String[] args) {
		// 1.创建服务对象
		ServerBootstrap serverBootstrap = new ServerBootstrap();
		// 2.创建两个线程池 第一个监听端口号 nio监听
		ExecutorService boss = Executors.newCachedThreadPool();
		ExecutorService work = Executors.newCachedThreadPool();
		// 3.将线程池放入工程
		serverBootstrap.setFactory(new NioServerSocketChannelFactory(boss, work));
		// 4.设置管道工程
		serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			// 设置管道
			@Override
			public ChannelPipeline getPipeline() throws Exception {
				ChannelPipeline pipeline = Channels.pipeline();
				// 传输数据的时候直接为string类型
				pipeline.addLast("decoder", new StringDecoder());
				pipeline.addLast("encoder", new StringDecoder());
				// 设置事件监听类
				pipeline.addLast("serverHandler", new ServerHandler());
				return pipeline;
			}
		});
		// 绑定端口号
		serverBootstrap.bind(new InetSocketAddress(8080));
		System.out.println("服务器端已经启动");
	}
}

class ServerHandler extends SimpleChannelHandler {

	// 通道被关闭的时候就会触发
	@Override
	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		// TODO Auto-generated method stub
		super.channelClosed(ctx, e);
		System.out.println("channelClosed");
	}

	// 必须要建立连接,关闭通道时候才会触发
	@Override
	public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		// TODO Auto-generated method stub
		super.channelDisconnected(ctx, e);
		System.out.println("channelDisconnected");
	}

	// 接收出现异常
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
		// TODO Auto-generated method stub
		super.exceptionCaught(ctx, e);
		e.getCause().printStackTrace();
		System.out.println("exceptionCaught:");
	}

	// 接收客户端数据
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		// TODO Auto-generated method stub
		super.messageReceived(ctx, e);
		System.out.println("messageReceived");
		System.out.println("服务器端获取客户端发来的参数" + e.getMessage());
		String msg = "Did you say '" + e.getMessage() + "'?\n";
		ChannelBuffer buffer = ChannelBuffers.buffer(msg.length());
		buffer.writeBytes(msg.getBytes());
		e.getChannel().write(buffer);
	}
}

2.netty3客户端

public class NettyClient {
	public static void main(String[] args) {
		// 1.创建服务对象
		ClientBootstrap clientBootstrap = new ClientBootstrap();
		// 2.创建两个线程池 第一个监听端口号 nio监听
		ExecutorService boss = Executors.newCachedThreadPool();
		ExecutorService work = Executors.newCachedThreadPool();
		// 3.将线程池放入工程
		clientBootstrap.setFactory(new NioClientSocketChannelFactory(boss, work));
		// 4.设置管道工程
		clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			// 设置管道
			@Override
			public ChannelPipeline getPipeline() throws Exception {
				ChannelPipeline pipeline = Channels.pipeline();
				// 传输数据的时候直接为string类型
				pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
				pipeline.addLast("encoder", new StringDecoder(CharsetUtil.UTF_8));
				// 设置事件监听类
				pipeline.addLast("clientHandler", new ClientHandler());
				return pipeline;
			}
		});
		// 绑定端口号
		ChannelFuture connect = clientBootstrap.connect(new InetSocketAddress("127.0.0.1", 8080));
		Channel channel = connect.getChannel();
		System.out.println("服务端启动");
		Scanner scanner = new Scanner(System.in);
		while (true) {
			System.out.println("请输入内容");
			String msg= scanner.next();
			 ChannelBuffer buffer = ChannelBuffers.buffer(msg.length());
			 buffer.writeBytes(msg.getBytes());
			 channel.write(buffer);
		}

	}
}

class ClientHandler extends SimpleChannelHandler {

	// 通道被关闭的时候就会触发
	@Override
	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		// TODO Auto-generated method stub
		super.channelClosed(ctx, e);
		System.out.println("channelClosed");
	}

	// 必须要建立连接,关闭通道时候才会触发
	@Override
	public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		// TODO Auto-generated method stub
		super.channelDisconnected(ctx, e);
		System.out.println("channelDisconnected");
	}

	// 接收出现异常
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
		// TODO Auto-generated method stub
		super.exceptionCaught(ctx, e);
		System.out.println("exceptionCaught");
	}

	// 接收客户端数据
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		// TODO Auto-generated method stub
		super.messageReceived(ctx, e);
		System.out.println("messageReceived");
		System.out.println("服务器端向客户端法律司的参数" + e.getMessage());

	}
}

三、使用netty5通信

1.netty5服务端

public class NettyServer {

	public static void main(String[] args) {
		System.out.println("服务器端启动....");
		try {
			// 1.创建两个线程池,一个负责接收客户端,一个进行传输
			NioEventLoopGroup pGroup = new NioEventLoopGroup();
			NioEventLoopGroup cGroup = new NioEventLoopGroup();
			// 2.创建辅助类
			ServerBootstrap b = new ServerBootstrap();
			b.group(pGroup, cGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024)
					// 3.设置缓冲区与发送区大小
					.option(ChannelOption.SO_SNDBUF, 32 * 1024).option(ChannelOption.SO_RCVBUF, 32 * 1024)
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel sc) throws Exception {
							//设置返回类型为String类型
							sc.pipeline().addLast(new StringDecoder());
							sc.pipeline().addLast(new ServerHandler());
						}
					});

			ChannelFuture cf = b.bind(8080).sync();
			cf.channel().closeFuture().sync();
			pGroup.shutdownGracefully();
			cGroup.shutdownGracefully();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
class ServerHandler extends ChannelHandlerAdapter{
	/** 
	 当通道被调用,执行方法(拿到数据)
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		super.channelRead(ctx, msg);
		String value = (String) msg;
		System.out.println("服务器端收到客户端msg:"+value);
		//回复客户端
		ctx.writeAndFlush("收到msg"+value);
	}
}

2、netty客户端

/**  
* @Package Netty5 
* @Title: NettyServer.java   
* @Description: TODO  
* @author pcm  
* @date 2018年6月12日 上午10:52:55
* @version V1.0  
*/
public class NettyClient {

	public static void main(String[] args) {
		System.out.println("客户端启动....");
		try {
			// 创建负责接收客户端连接
			NioEventLoopGroup pGroup = new NioEventLoopGroup();
			Bootstrap b = new Bootstrap();
			b.group(pGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel sc) throws Exception {
					// 设置返回类型为String类型
					sc.pipeline().addLast(new StringDecoder());
					sc.pipeline().addLast(new ClientHandler());
				}
			});
            
			ChannelFuture cf = b.connect("127.0.0.1",8080).sync();
			cf.channel().writeAndFlush(Unpooled.wrappedBuffer("123".getBytes()));
			cf.channel().writeAndFlush(Unpooled.wrappedBuffer("我是客户端".getBytes()));
			cf.channel().closeFuture().sync();
			pGroup.shutdownGracefully();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

class ClientHandler extends ChannelHandlerAdapter {
	/** 
	 当通道被调用,执行方法
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		super.channelRead(ctx, msg);
		// 接收数据
		String value = (String) msg;
		System.out.println("client msg" + value);
	}
}