【传统BIO通信模型图】
package com.cherry.socket.bio;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author [email protected]
* @create 2018/4/13 9:24
* @desc
**/
public class BIOServerBootStrap {
public static void main(String[] args) throws IOException {
//1.Create ServerSocket
ServerSocket serverSocket = new ServerSocket();
//2.Set up the service listener port
serverSocket.bind(new InetSocketAddress(9999));
//Create a thread pool
ExecutorService threadPool = Executors.newFixedThreadPool(150);
while (true){
//3.Waitting for request
System.out.println("----waitting for request----");
final Socket socket = serverSocket.accept();
threadPool.submit(new Runnable() {
public void run() {
try {
//4.Obtain user intent
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line=br.readLine())!=null){
sb.append(line);
}
System.out.println("----the message get by server---- : "+sb);
//5.client response
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.println("server time"+new Date().toLocaleString());
pw.flush();
socket.shutdownOutput();//Tell the client to write the cut-off
//6.release the resource
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
}
package com.cherry.socket.bio;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
/**
* @author [email protected]
* @create 2018/4/13 11:07
* @desc
**/
public class BIOClientBootStrap {
public static void main(String[] args) throws IOException {
//1.Create client socket
Socket socket = new Socket();
//2.connect to the server
socket.connect(new InetSocketAddress("127.0.0.1",9999));
//3.makes requests to the server
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.println("Hello,This is Client 2");
pw.flush();
socket.shutdownOutput();//Tell the Server to write the cut-off
//4.get the response
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line =null;
while ((line=br.readLine())!=null){
sb.append(line);
}
System.out.println("----The message get by client---- : "+sb);
//5.release the resource
socket.close();
}
}
package com.cherry.socket.nio;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
/**
* @author [email protected]
* @create 2018/4/13 11:34
* @desc
**/
public class NIOServerBootStrap {
public static void main(String[] args) throws IOException {
//1.Create ServerSocketChannel
ServerSocketChannel ssc = ServerSocketChannel.open();
//2.Set up the service listener port
ssc.socket().bind(new InetSocketAddress(9999));
//3.Set up the channel to be non-blocking
ssc.configureBlocking(false);
//4.Create channel selector
Selector selector =Selector.open();
//5.注册事件类型
ssc.register(selector, SelectionKey.OP_ACCEPT);
//6.遍历事件处理列表
while (true){
int num = selector.select();
if (num>0){
//获取所有待处理的keys
Iterator keys = selector.selectedKeys().iterator();
while (keys.hasNext()){
SelectionKey key = keys.next();
//处理事件
if(key.isAcceptable()){
System.out.println("----key isAcceptable----");
ServerSocketChannel channel = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = channel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector,SelectionKey.OP_ACCEPT);
}else if (key.isReadable()){
System.out.println("----key isReadable(read)----");
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (true){
buffer.clear();
int n = channel.read(buffer);
if (n==1)break;
baos.write(buffer.array(),0,n);
}
channel.register(selector,SelectionKey.OP_WRITE,baos);
} else if (key.isWritable()){
System.out.println("----key isWritable(write)----");
SocketChannel channel = (SocketChannel) key.channel();
ByteArrayOutputStream baos = (ByteArrayOutputStream) key.attachment();
baos.write("_服务器追加".getBytes());
ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray());
channel.write(buffer);
channel.socket().shutdownOutput();
channel.close();
}
//移除时间列表
keys.remove();
}
} else {
continue;
}
}
}
}
package com.cherry.socket.netty.server;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
* @author [email protected]
* @create 2018/4/16 9:51
* @desc
**/
public class ServerBootStrap {
public static void main(String[] args) throws InterruptedException {
//1.Create ServerBootstrap
ServerBootstrap sbt = new ServerBootstrap();
//2.Create thread pool(boss & worker)
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup worker = new NioEventLoopGroup();
//3.关联线程池(boss负责请求转发,worker负责事件处理)
sbt.group(boss,worker);
//4.Set up the server
sbt.channel(NioServerSocketChannel.class);
//5.Initialize the communication channel (key point)
sbt.childHandler(new ServerChannelInitizlizer());
//6.Bind listening port
System.out.println("我在@9999端口监听...");
ChannelFuture channelFuture = sbt.bind(9999).sync();
//7.Wait for the server to close
channelFuture.channel().closeFuture().sync();
//l
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
package com.cherry.socket.netty.server;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
/**
* @author [email protected]
* @create 2018/4/16 10:26
* @desc
**/
public class ServerChannelHander extends ChannelHandlerAdapter {
/*捕获数据在通道传输过程中的异常*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.err.println("错误:"+cause.getMessage());
}
/*接收数据,并响应*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ChannelFuture channelFuture = ctx.writeAndFlush(msg);
//关闭通道
channelFuture.addListener(ChannelFutureListener.CLOSE);
}
}
package com.cherry.socket.netty.server;
import com.cherry.socket.netty.server.ServerChannelHander;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
/**
* @author [email protected]
* @create 2018/4/16 10:02
* @desc
**/
public class ServerChannelInitizlizer extends ChannelInitializer {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//communication channel
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new ServerChannelHander());
}
}
package com.cherry.socket.netty.client;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
/**
* @author [email protected]
* @create 2018/4/16 11:15
* @desc
**/
public class ClientBootStrap {
public static void main(String[] args) throws InterruptedException {
//1.Create Bootstrap
Bootstrap bt = new Bootstrap();
//2.Create thread pool(worker)
EventLoopGroup worker = new NioEventLoopGroup();
//3.关联线程池
bt.group(worker);
//4.Set up the client
bt.channel(NioSocketChannel.class);
//5.Initialize the communication channel (key point)
bt.handler(new ClientChannelInitializer());
//6.连接
ChannelFuture channelFuture = bt.connect("127.0.0.1",9999).sync();
//7.Wait for the server to close
channelFuture.channel().closeFuture().sync();
//8.release the resource
worker.shutdownGracefully();
}
}
package com.cherry.socket.netty.client;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.CharsetUtil;
import javax.xml.transform.Source;
/**
* @author [email protected]
* @create 2018/4/16 11:22
* @desc
**/
public class ClientChannelHander extends ChannelHandlerAdapter {
/*捕获数据在通道传输过程的异常*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//super.exceptionCaught(ctx, cause);
System.out.println("错误:"+cause.getMessage());
}
/*接收数据*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//super.channelRead(ctx, msg);
ByteBuf byteBuf = (ByteBuf) msg;
System.out.println(((ByteBuf)msg).toString(CharsetUtil.UTF_8));
}
/*链接服务器时发送数据*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//super.channelActive(ctx);
ByteBuf buf = Unpooled.buffer();
buf.writeBytes("你好,我是客户端!".getBytes());
ctx.writeAndFlush(buf);
}
}
package com.cherry.socket.netty.client;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
/**
* @author [email protected]
* @create 2018/4/16 11:20
* @desc
**/
public class ClientChannelInitializer extends ChannelInitializer {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//communication channel
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new ClientChannelHander());
}
}
io.netty
netty-all
5.0.0.Alpha2