当前位置:网站首页>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 .
边栏推荐
- Day 248/300 关于毕业生如何找工作的思考
- Successfully solved typeerror: data type 'category' not understood
- How to convert flv file to MP4 file? A simple solution
- 因高额网络费用,Arbitrum 奥德赛活动暂停,Nitro 发行迫在眉睫
- Attributeerror successfully resolved: can only use cat accessor with a ‘category‘ dtype
- Due to high network costs, arbitrum Odyssey activities are suspended, and nitro release is imminent
- 软件测试外包到底要不要去?三年真实外包感受告诉你
- 成功解决AttributeError: Can only use .cat accessor with a ‘category‘ dtype
- 前缀和数组系列
- 【每日一题】729. 我的日程安排表 I
猜你喜欢
基于PyTorch和Fast RCNN快速实现目标识别
Attributeerror: can 't get attribute' sppf 'on < module' models. Common 'from' / home / yolov5 / Models / comm
Blue Bridge Cup zero Foundation National Championship - day 20
机器学习植物叶片识别
19. Actual memory management of segment page combination
18.多级页表与快表
AttributeError: Can‘t get attribute ‘SPPF‘ on <module ‘models. common‘ from ‘/home/yolov5/models/comm
hydra常用命令
[ 英语 ] 语法重塑 之 英语学习的核心框架 —— 英语兔学习笔记(1)
Development of entity developer database application
随机推荐
我的创作纪念日
Fast target recognition based on pytorch and fast RCNN
PCL实现选框裁剪点云
Entity Developer数据库应用程序的开发
Attributeerror successfully resolved: can only use cat accessor with a ‘category‘ dtype
At the age of 26, I changed my career from finance to software testing. After four years of precipitation, I have been a 25K Test Development Engineer
SQL Server manager studio(SSMS)安装教程
UNIPRO Gantt chart "first experience": multi scene exploration behind attention to details
Erreur de type résolue avec succès: type de données « catégorie» non sous - jacente
AttributeError: Can‘t get attribute ‘SPPF‘ on <module ‘models.common‘ from ‘/home/yolov5/models/comm
Biomedical English contract translation, characteristics of Vocabulary Translation
Py06 dictionary mapping dictionary nested key does not exist test key sorting
Market segmentation of supermarket customers based on purchase behavior data (RFM model)
详解SQL中Groupings Sets 语句的功能和底层实现逻辑
简单描述 MySQL 中,索引,主键,唯一索引,联合索引 的区别,对数据库的性能有什么影响(从读写两方面)
SSO流程分析
雲上有AI,讓地球科學研究更省力
【Hot100】739. 每日温度
成功解决TypeError: data type ‘category‘ not understood
前缀和数组系列