代码分为两部分
第一部分:服务端,用于接收和发送消息,并且监听客户端是否在线
package com.company;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Line_Tcp {
public static void main(String[] args) throws IOException {
// 创建服务端套接字对象
ServerSocket serverSocket = new ServerSocket(10081);
System.out.println("服务端已上线");
// 监听客户端
Socket socket = serverSocket.accept();
// 创建一个线程池来进行发送和接收消息
ThreadPoolExecutor tpe = new ThreadPoolExecutor(2, 4, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
// 首先发送消息
tpe.execute(() ->{
Scanner scanner = new Scanner(System.in);
try {
OutputStream outputStream = socket.getOutputStream();
while(true) {
System.out.println("请输入你要发送的内容");
String content = scanner.nextLine();
outputStream.write(content.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}
});
// 在使用一个线程来接收消息
tpe.execute(() ->{
try {
InputStream inputStream = socket.getInputStream();
byte[] buf = new byte[1024*4];
while (true){
int read = inputStream.read(buf);
System.out.println("客户端: " + new String(buf,0,read));
}
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
第二部分:客户端,用于接收和发送消息
package com.company;
import jdk.nashorn.internal.ir.WhileNode;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Client_Tcp {
public static void main(String[] args) throws IOException {
// 创建Socket套接字
Socket socket = new Socket(InetAddress.getLocalHost(),10081);
System.out.println("客户端上线");
// 创建一个线程池来接收和发送消息
ThreadPoolExecutor tpe = new ThreadPoolExecutor(2, 4, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
// 第一个线程用来接收消息
tpe.execute(() ->{
// 创建一个字节输入流来读取消息
try {
InputStream inputStream = socket.getInputStream();
// 创建一个Byte数组用来读取消息
byte[] buf = new byte[1024 * 4];
while(true) {
int read = inputStream.read(buf);
System.out.println(new String(buf, 0, read));
}
} catch (IOException e) {
e.printStackTrace();
}
});
// 第二个线程用来发送消息
tpe.execute(() ->{
Scanner scanner = new Scanner(System.in);
try {
OutputStream outputStream = socket.getOutputStream();
while(true) {
System.out.println("请输入你要发送的内容");
String concent = scanner.nextLine();
outputStream.write(concent.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
最后实现图如下: