1,netty是Jboss出品 ,是Github上的独立项目
2,netty是异步的,是基于事件驱动的
3,基于TCP/IP协议的,
4,如图所示是netty的结构。
BIO同步的阻塞,一个连接就要一个线程,如果线程,开销很大。
IO模型
5,bio的server代码
package bio;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class BIOServer {
public static void main(String[] args) throws IOException {
//使用线程池机制
//如果有一个客户端请求,我们就创建线程。
ExecutorService pool = Executors.newCachedThreadPool();
//创建一个socket
ServerSocket serverSocket = new ServerSocket(3434);
System.out.println("server start-------------");
AtomicInteger count = new AtomicInteger(0);
while (true) {
System.out.println("等待连接。。。。。。。");
Socket accept = serverSocket.accept();
System.out.println(count.getAndIncrement()+"++++++++++++");
pool.execute(()->{handler(accept);});
}
}
public static void handler(Socket socket) {
try {
System.out.println(Thread.currentThread().getName()+"线程:"+Thread.currentThread().getId());
byte[] bytes = new byte[1024];
InputStream inputStream = socket.getInputStream();
while (true) {
System.out.println("while true zhongde :"+Thread.currentThread().getName()+"线程:"+Thread.currentThread().getId());
System.out.println("等待输入。。。。。。。。。");
int read = inputStream.read(bytes);
if (read != -1) {
System.out.println(new String(bytes, 0, read));
}else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
System.out.println("关闭了client的连接");
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
主要是主线程等待连接。
有链接给client一个线程,做通讯,如果client没有输入一直等待
缺点:在client特别多的时候,会出现线程占用过多。如果client没有输入,造成等待的浪费了。