当前位置:网站首页>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 .
边栏推荐
- Fedora/rehl installation semanage
- LeetCode每日一题(1997. First Day Where You Have Been in All the Rooms)
- 雲上有AI,讓地球科學研究更省力
- Monotonic stack
- Successfully solved typeerror: data type 'category' not understood
- Is it difficult for girls to learn software testing? The threshold for entry is low, and learning is relatively simple
- Reflex WMS中阶系列3:显示已发货可换组
- 简单描述 MySQL 中,索引,主键,唯一索引,联合索引 的区别,对数据库的性能有什么影响(从读写两方面)
- Machine learning plant leaf recognition
- 中青看点阅读新闻
猜你喜欢
A method to measure the similarity of time series: from Euclidean distance to DTW and its variants
Oracle数据库11gr2使用tde透明数据加密报错ora28353,如果运行关闭wallet会报错ora28365,运行打开wallet就报错ora28353无法打开wallet
开源的网易云音乐API项目都是怎么实现的?
AttributeError: Can‘t get attribute ‘SPPF‘ on <module ‘models.common‘ from ‘/home/yolov5/models/comm
基于PyTorch和Fast RCNN快速实现目标识别
mysql的基础命令
On the first day of clock in, click to open a surprise, and the switch statement is explained in detail
攻防世界 MISC中reverseMe简述
漏了监控:Zabbix对Eureka instance状态监控
BUU的MISC(不定时更新)
随机推荐
Fast target recognition based on pytorch and fast RCNN
将ue4程序嵌入qt界面显示
[brush questions] how can we correctly meet the interview?
UDP攻击是什么意思?UDP攻击防范措施
LeetCode - 152 乘积最大子数组
我的创作纪念日
Erreur de type résolue avec succès: type de données « catégorie» non sous - jacente
【Hot100】739. Daily temperature
顶测分享:想转行,这些问题一定要考虑清楚!
Machine learning plant leaf recognition
万丈高楼平地起,每个API皆根基
SSO process analysis
19.段页结合的实际内存管理
A method to measure the similarity of time series: from Euclidean distance to DTW and its variants
18.多级页表与快表
ROS2安装及基础知识介绍
hydra常用命令
18. Multi level page table and fast table
19. Actual memory management of segment page combination
Pallet management in SAP SD delivery process