当前位置:网站首页>Bio model realizes multi person chat
Bio model realizes multi person chat
2022-07-06 06:55:00 【qq_ forty-four million one hundred and sixteen thousand five hu】
1、 Server side
package com.li.server;
import jdk.net.Sockets;
import javax.sound.sampled.Port;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
/**
* @author liyakun
*/
public class ChatServer {
private int DEFAULT_PORT = 8886;
private final String QUIT = "quit";
private ServerSocket serverSocket;
private Map<Integer, Writer> connectedClients;
public ChatServer() {
connectedClients = new HashMap<Integer, Writer>();
}
public synchronized void addClient(Socket socket) throws IOException {
if (socket != null) {
int port = socket.getPort();
BufferedWriter bufferedWriter = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())
);
connectedClients.put(port, bufferedWriter);
System.out.println(" Port number :" + port + " Connected to server ");
}
}
public synchronized void removeServer(Socket socket) throws IOException {
if (socket != null) {
int port = socket.getPort();
if (connectedClients.containsKey(port)) {
connectedClients.get(port).close();
}
connectedClients.remove(port);
System.out.println(" client " + port + " Offline ");
}
}
public synchronized void forwardMessage(Socket socket, String fwdMsg) throws IOException {
for (Integer integer : connectedClients.keySet()) {
if (!integer.equals(socket.getPort())) {
Writer writer = connectedClients.get(integer);
writer.write(fwdMsg);
writer.flush();
}
}
}
/**
* Check whether the user exits
* @param msg
* @return
*/
public boolean readyToQuit(String msg) {
return QUIT.equals(msg);
}
public void close() {
if (serverSocket != null) {
try {
serverSocket.close();
System.out.println(" close serverSocket");
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void start() {
try {
serverSocket = new ServerSocket(DEFAULT_PORT);
System.out.println(" Server startup , Listening port " + DEFAULT_PORT);
while (true) {
// Wait for the client to connect
Socket socket = serverSocket.accept();
// establish chatHandler Threads
new Thread(new ChatHandler(this,socket)).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
close();
}
}
public static void main(String[] args) {
ChatServer chatServer = new ChatServer();
chatServer.start();
}
}
package com.li.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
/**
* @author liyakun
*/
public class ChatHandler implements Runnable {
private ChatServer chatServer;
private Socket socket;
public ChatHandler(ChatServer chatServer, Socket socket) {
this.chatServer = chatServer;
this.socket = socket;
}
@Override
public void run() {
try {
// Store new online users
chatServer.addClient(socket);
// Read the information sent by the user
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg=null;
while ((msg=bufferedReader.readLine())!=null){
String fwdMsg=" client 【"+socket.getPort()+"]"+msg+"\n";
System.out.println(fwdMsg);
chatServer.forwardMessage(socket,fwdMsg);
// Check whether the user exits
if(chatServer.readyToQuit(msg)){
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
chatServer.removeServer(socket);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2、 client
package com.li.client;
import java.io.*;
import java.net.Socket;
/**
* @author liyakun
*/
public class ChatClient {
private final String DEFAULT_SERVER_HOST = "127.0.0.1";
private final int DEFAULT_SERVER_PORT = 8886;
private final String QUIT = "quit";
private Socket socket;
private BufferedReader reader;
private BufferedWriter writer;
// Send information to the server
public void send(String msg) throws IOException {
if (!socket.isOutputShutdown()) {
writer.write(msg + "\n");
writer.flush();
}
}
public String receive() throws IOException {
String msg = null;
if (!socket.isInputShutdown()) {
msg = reader.readLine();
}
return msg;
}
// Check whether the user is ready to exit
public boolean readyToQuit(String msg) {
return QUIT.equals(msg);
}
public void close() {
if (writer != null) {
try {
System.out.println(" close socket");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void start() {
try {
// establish socket
socket = new Socket(DEFAULT_SERVER_HOST, DEFAULT_SERVER_PORT);
// establish IO flow
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// Processing user input
new Thread(new UserInputHandler(this)).start();
// Read the information forwarded by the server
String msg = null;
while ((msg = receive()) != null) {
System.out.println(msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ChatClient chatClient = new ChatClient();
chatClient.start();
}
}
package com.li.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author liyakun
*/
public class UserInputHandler implements Runnable {
private ChatClient chatClient;
public UserInputHandler(ChatClient chatClient) {
this.chatClient = chatClient;
}
@Override
public void run() {
try {
// Waiting for user input
BufferedReader consoleReader =
new BufferedReader(new InputStreamReader(System.in));
while (true) {
String input = consoleReader.readLine();
// Send a message to the server
chatClient.send(input);
// Check whether the user is ready to exit
if (chatClient.readyToQuit(input)) {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
3、 test :
stay IDEA Running server in , And open multiple clients ( Opening method editConfigurations------>Allow parallel run), You can test successfully .
边栏推荐
- The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
- Reflex WMS中阶系列3:显示已发货可换组
- BIO模型实现多人聊天
- Leetcode daily question (1870. minimum speed to arrive on time)
- GET 和 POST 请求类型的区别
- Entity Developer数据库应用程序的开发
- Facebook AI & Oxford proposed a video transformer with "track attention" to perform SOTA in video action recognition tasks
- 女生学软件测试难不难 入门门槛低,学起来还是比较简单的
- [ 英语 ] 语法重塑 之 动词分类 —— 英语兔学习笔记(2)
- PCL实现选框裁剪点云
猜你喜欢

RichView TRVStyle 模板样式的设置与使用

A method to measure the similarity of time series: from Euclidean distance to DTW and its variants

机器学习植物叶片识别

L'Ia dans les nuages rend la recherche géoscientifique plus facile

18.多级页表与快表

AttributeError: Can‘t get attribute ‘SPPF‘ on <module ‘models. common‘ from ‘/home/yolov5/models/comm

漏了监控:Zabbix对Eureka instance状态监控

Chapter 7 - thread pool of shared model

What is the difference between int (1) and int (10)? Senior developers can't tell!

Database basics exercise part 2
随机推荐
云上有AI,让地球科学研究更省力
Three methods of adding color to latex text
mysql的基础命令
Attributeerror successfully resolved: can only use cat accessor with a ‘category‘ dtype
UNIPRO Gantt chart "first experience": multi scene exploration behind attention to details
医疗软件检测机构怎么找,一航软件测评是专家
How to reconstruct the class explosion caused by m*n strategies?
The registration password of day 239/300 is 8~14 alphanumeric and punctuation, and at least 2 checks are included
指尖上的 NFT|在 G2 上评价 Ambire,有机会获得限量版收藏品
[Yu Yue education] Dunhuang Literature and art reference materials of Zhejiang Normal University
Database basics exercise part 2
[daily question] 729 My schedule I
Number of query fields
因高额网络费用,Arbitrum 奥德赛活动暂停,Nitro 发行迫在眉睫
My creation anniversary
19. Actual memory management of segment page combination
接口自动化测试实践指导(上):接口自动化需要做哪些准备工作
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
Practical guidance for interface automation testing (Part I): what preparations should be made for interface automation
Simple use of MySQL database: add, delete, modify and query