当前位置:网站首页>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 .
边栏推荐
- 将ue4程序嵌入qt界面显示
- Biomedical English contract translation, characteristics of Vocabulary Translation
- 《从0到1:CTFer成长之路》书籍配套题目(周更)
- Call, apply, bind rewrite, easy to understand with comments
- Reflex WMS中阶系列3:显示已发货可换组
- Every API has its foundation when a building rises from the ground
- SSO流程分析
- Blue Bridge Cup zero Foundation National Championship - day 20
- Leetcode - 152 product maximum subarray
- [brush questions] how can we correctly meet the interview?
猜你喜欢

Supporting title of the book from 0 to 1: ctfer's growth road (Zhou Geng)

SQL Server manager studio(SSMS)安装教程

接口自动化测试框架:Pytest+Allure+Excel

Leetcode daily question (971. flip binary tree to match preorder traversal)
![[brush questions] how can we correctly meet the interview?](/img/89/a5b874ba4db97fbb3d330af59c387a.png)
[brush questions] how can we correctly meet the interview?

mysql的基础命令

Office doc add in - Online CS

How to convert flv file to MP4 file? A simple solution

【每日一题】729. 我的日程安排表 I

Fedora/REHL 安装 semanage
随机推荐
SSO process analysis
成功解决AttributeError: Can only use .cat accessor with a ‘category‘ dtype
The difference between get and post request types
PCL实现选框裁剪点云
开源的网易云音乐API项目都是怎么实现的?
基于PyTorch和Fast RCNN快速实现目标识别
C语言_双创建、前插,尾插,遍历,删除
Do you really know the use of idea?
L'Ia dans les nuages rend la recherche géoscientifique plus facile
Redis Foundation
Arduino tutorial - Simon games
Day 248/300 thoughts on how graduates find jobs
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
Leetcode daily question (1870. minimum speed to arrive on time)
Briefly describe the differences between indexes, primary keys, unique indexes, and joint indexes in mysql, and how they affect the performance of the database (in terms of reading and writing)
Practical guidance for interface automation testing (Part I): what preparations should be made for interface automation
【软件测试进阶第1步】自动化测试基础知识
攻防世界 MISC中reverseMe简述
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
Development of entity developer database application