服务端:
@Data
@Component
public class DelongServerSocket {
@Value("${socket.port}")
private Integer port;
private boolean started;
private ServerSocket ss;
public static ConcurrentHashMap<String, ClientSocket> clientsMap = new ConcurrentHashMap<>();
private ExecutorService executorService = Executors.newCachedThreadPool();

public static void main(String[] args) {
System.out.println("进入main:");
new DelongServerSocket().start(10086);
}

public void start() {
start(null);
}

public void start(Integer port) {
try {
ss = new ServerSocket(port == null ? this.port : port);
started = true;
System.out.println("端口已开启,占用端口号...."+this.port);
} catch (Exception e) {
System.out.println("端口使用中....");
System.out.println("请关掉相关程序并重新运行服务器!");
e.printStackTrace();
System.exit(0);
}
int count = 0;
try {
while (started) {
Socket socket = ss.accept();
socket.setKeepAlive(true);
count++;
ClientSocket register = ClientSocket.register(socket,count);
System.out.println("a client connected!");
if (register != null) {
executorService.submit(register);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

客户端线程:
@Data
@Slf4j
public class ClientSocket implements Runnable {

private Socket socket;
private DataInputStream inputStream;
private DataOutputStream outputStream;
private String key;
private String message;

/**
* 注册socket到map里
*
* @param socket
* @return
*/
public static ClientSocket register(Socket socket,int count) throws Exception {
ClientSocket client = new ClientSocket();
try {
client.setSocket(socket);
client.setInputStream(new DataInputStream(socket.getInputStream()));
client.setOutputStream(new DataOutputStream(socket.getOutputStream()));
System.out.println("客户端的IP:"+socket.getInetAddress().getHostAddress());
System.out.println("user" + count+"正在登录...");
client.setKey("user"+count);
DelongServerSocket.clientsMap.put(client.getKey(), client);
System.out.println(DelongServerSocket.clientsMap);
return client;
} catch (Exception e) {
client.logout();
}
return null;
}

/**
* 发送数据
*
* @param str
*/
public void send(String str) throws Exception {
System.out.println("服务端发送:======" + str);
try {
outputStream.write(str.getBytes());
} catch (Exception e) {
logout();
}
}

/**
* 接收数据
*
* @return
* @throws Exception
*/
public String receive() throws Exception {
try {
byte[] bytes = new byte[1024];
inputStream.read(bytes);
String info = new String(bytes, "utf-8");
System.out.println("服务端接收:===" + info);
return info;
} catch (Exception e) {
logout();
}
return null;
}

/**
* 登出操作, 关闭各种流
*/
public void logout() throws Exception {
if (DelongServerSocket.clientsMap.containsKey(key)) {
DelongServerSocket.clientsMap.remove(key);
}

System.out.println(DelongServerSocket.clientsMap);
try {
// socket.shutdownOutput();
// socket.shutdownInput();
inputStream.close();
outputStream.close();
} catch (Exception e) {
throw new Exception("关闭输入输出异常", e);
} finally {
try {
socket.close();
} catch (Exception e) {
throw new Exception("关闭socket异常", e);
}
}
}

/**
* 发送数据包, 判断数据连接状态
*
* @return
*/
public boolean isSocketClosed() {
try {
//socket.sendUrgentData(1);
//发送
Socket socket1 = DelongServerSocket.clientsMap.get("user1").getSocket();
socket1.getOutputStream().write("测试1".getBytes(StandardCharsets.UTF_8));
//socket.getOutputStream().write("测试".getBytes(StandardCharsets.UTF_8));
//接收
byte[] bytes = new byte[1024];
socket.getInputStream().read(bytes);
String receive = new String(bytes, "utf-8");
System.out.println("服务端接收消息" + receive);
return false;
} catch (Exception e) {
return true;
}
}

@Override
public void run() {
// 每过5秒连接一次客户端
while (true) {
try {
TimeUnit.SECONDS.sleep(5);
if (isSocketClosed()) {
System.out.println("关闭");
logout();
break;
}
} catch (Exception e) {
e.printStackTrace();
}

}

}

@Override
public String toString() {
return "Client{" +
"socket=" + socket +
", inputStream=" + inputStream +
", outputStream=" + outputStream +
", key='" + key + '\'' +
'}';
}

}

客户端1:
public class ChatClient {
public static void main(String[] args) throws Exception {
String host = "127.0.0.1";
int port = 8082;
// 与服务端建立连接
Socket socket = new Socket(host, port);
socket.setOOBInline(true);
// 建立连接后获得输出流
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
int i=0;
while (true) {
send("客户端测试"+i,outputStream);
receive(inputStream);
i++;
}
}

/**
* 发送数据
*
* @param str
*/
public static void send(String str,DataOutputStream outputStream) throws Exception {
System.out.println("客户端发送:======"+str);
try {
outputStream.write(str.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 接收数据
*
* @return
* @throws Exception
*/
public static String receive(DataInputStream inputStream) throws Exception {
try {
byte[] bytes = new byte[1024];
inputStream.read(bytes);
String info = new String(bytes, "utf-8");
System.out.println("客户端接收:==="+info);
return info;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

}

客户端2:
public class ChatClient2 {
public static void main(String[] args) throws Exception {
String host = "127.0.0.1";
int port = 8082;
// 与服务端建立连接
Socket socket = new Socket(host, port);
socket.setOOBInline(true);
// 建立连接后获得输出流
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
int i=0;
while (true) {
send("客户端2测试"+i,outputStream);
//receive(inputStream);
i++;
}
}

/**
* 发送数据
*
* @param str
*/
public static void send(String str,DataOutputStream outputStream) throws Exception {
System.out.println("客户端发送:======"+str);
try {
outputStream.write(str.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 接收数据
*
* @return
* @throws Exception
*/
public static String receive(DataInputStream inputStream) throws Exception {
try {
byte[] bytes = new byte[1024];
inputStream.read(bytes);
String info = new String(bytes, "utf-8");
System.out.println("客户端接收:==="+info);
return info;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

}


服务端启动:

@SpringBootApplication
@Controller
public class DemoApplication {

public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(DemoApplication.class, args);
context.getBean(DelongServerSocket.class).start();

}

}