要深入研究netty所以先写个BIO的服务端客户端之后做对比(可以多个客户端运行)
三个类
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static String IP = "127.0.0.1";
public static int PORT = 12378;
public static void main(String[] args) {
try {
Socket socket = new Socket(IP, PORT);
System.out.println("请输出数据");
new ReadMsg(socket).start();
while (true) {
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.println(new Scanner(System.in).next());
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static class ReadMsg extends Thread {
private Socket socket;
ReadMsg(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
BufferedReader reader1 = new BufferedReader( new InputStreamReader(socket.getInputStream()));
String line = null;
while ((line = reader1.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
clear();
}
}
//必要的资源清理工作
private void clear() {
if (socket != null)
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server {
private static ServerSocket server;
public static String IP = "127.0.0.1";
public static int PORT = 12378;
public static ExecutorService executorService = Executors.newFixedThreadPool(5);
public static void start() throws IOException {
try {
server = new ServerSocket(PORT);
while (true) {
System.out.println("建立新连接");
Socket socket = server.accept();
executorService.execute(new ServerHandle(socket));
}
//Socket socket = server.accept();
} catch (IOException e) {
e.printStackTrace();
}
finally{
if(server!=null){
server.close();
}
}
}
public static void main(String[] args) throws IOException {
start();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ServerHandle implements Runnable {
private Socket socket;
ServerHandle (Socket socket)
{
this.socket=socket;
}
@Override
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
String message;
String result;
while((message=reader.readLine()) !=null)
{
System.out.println("服务器收到数据:"+message);
writer.println(message);
}
} catch (IOException e) {
e.printStackTrace();
}
finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
socket = null;
}
}
}
}
可以多开两个客户端测试。