1 Netty是什么
- 异步事件驱动框架,用于快速开发高性能服务端和客户端
- 封装了JDK底层BIO和NIO模型,提供高度可用的API
- 自带编解码器解决拆包粘包问题,用户只用关心业务逻辑
- 精心设计的reactor线程模型支持高并发海量连接
- 自带各种协议栈让你处理任何一种通信协议都几乎不用亲自动手
2 一个简单的socket例子
这是一个简单I/O的例子
/**
* Server端启动类
* @author mazhen
*/
public class ServerBoot {
private static final int PORT = 10000;
public static void main(String[] args) {
Server server = new Server(PORT);
server.start();
}
}
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private ServerSocket serverSocket;
public Server(int port) {
try {
this.serverSocket = new ServerSocket(port);
System.out.println("服务端启动成功,端口:" + port);
} catch (IOException exception) {
System.out.println("服务端启动失败");
}
}
public void start() {
doStart();
System.out.println("无法执行到我?");
}
private void doStart() {
while (true) {
try {
//serverSocket获取客户端的请求并获取客户端Socket
Socket client = serverSocket.accept();
new ClientHandler(client).start();
} catch (IOException e) {
System.out.println("服务端异常");
}
}
}
}
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class ClientHandler {
public static final int MAX_DATA_LEN = 1024;
private final Socket socket;
public ClientHandler(Socket socket) {
this.socket = socket;
}
public void start() {
System.out.println("新客户端接入");
//启动一个线程,读取Socket中的输入流
new Thread(this::doStart).start();
}
private void doStart() {
try {
InputStream inputStream = socket.getInputStream();
while (true) {
byte[] data = new byte[MAX_DATA_LEN];
int len;
while ((len = inputStream.read(data)) != -1) {
String message = new String(data, 0, len);
System.out.println("客户端传来消息: " + message);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.net.Socket;
/**
* @author 闪电侠
*/
public class Client {
private static final String HOST = "127.0.0.1";
private static final int PORT = 10000;
private static final int SLEEP_TIME = 5000;
public static void main(String[] args) throws IOException {
final Socket socket = new Socket(HOST, PORT);
new Thread(() -> {
System.out.println("客户端启动成功!");
while (true) {
try {
String message = "hello world";
System.out.println("客户端发送数据: " + message);
socket.getOutputStream().write(message.getBytes());
} catch (Exception e) {
System.out.println("写数据出错!");
}
sleep();
}
}).start();
}
private static void sleep() {
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}