【Socket聊天室项目】while(true)循环效率问题

qq_36172692 qq_36172692 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
话不多说先上图


自己在写一个web项目要用到聊天功能,我在项目里面用到了一些while(true)样子的循环。每个客户端Socket我建了两个线程,一个用来监听客户端发来的信息,另一个用来监听别人发给客户端的信息(上图就是将别人存在本地的消息队列发送给客户端)。

这里用到了很多while(true)结构的循环,请问一下各位大佬,开启服务器后我发现开了200个客户端,服务器就会卡的shi一样,明显是while死循环太多造成的,有没有什么好的办法可以解决while循环多了效率会下降的问题?或者有什么办法可以代替while循环?

public class SocketListener {
/*
随Tomcat启动,准备100个端口,每个端口启动一个ServerSocket线程
*/
public static ArrayList<SoloServerSocketThread> SERVERS = new ArrayList<>();
public SocketListener() throws IOException {
for(int i=20001;i<=20100;i++){
SERVERS.add(new SoloServerSocketThread(i));
}
}


}


public class SoloClientSocketThread implements Runnable {
private Socket client;
private InputStream earphone;
private PrintStream microphone;
private Queue<String> speakQueue = new LinkedList<>();
private Queue<String> messageCache = new LinkedList<>();

private Long commitTime = System.currentTimeMillis();

/*
每一个人在一个时间点存在一个连接是打开中的状态,
*/
public Socket getClient() {
return client;
}

public SoloClientSocketThread(Socket client) throws IOException {
this.client = client;
earphone = client.getInputStream();
microphone = new PrintStream(client.getOutputStream());
new Thread(() -> {
while (!client.isClosed()) {
Long nowTime = System.currentTimeMillis();
if (nowTime > commitTime - 5 || nowTime < commitTime + 5) {//有没有更好的方法监听是否有消息传来?
String temp;
while ((temp = messageCache.poll()) != null) {
microphone.println(temp);
}
}
}
}).start();
}


public void destory() throws IOException {
earphone.close();
microphone.close();
client.close();
}

public boolean isDestoried() {
return client.isClosed();
}

public ArrayList<String> broadcast() {
//这个是发送方法,服务器主动读取客户端传来的消息。
ArrayList<String> list = new ArrayList<>();
String temp;
while ((temp = speakQueue.poll()) != null) {
list.add(temp);
}
return list.size() == 0 ? null : list;
}

public void record(String record) {
//这个是接收方法,外部找到对应对象之后调用则个方法可以将消息添加到队列,并给客户端发送过去
messageCache.add(record);
commitTime = System.currentTimeMillis() + 1000;
}

@Override
public void run() {
int b;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
while (!client.isClosed()) {
if ((b = earphone.read()) == '\n') {
speakQueue.add(baos.toString());
baos = new ByteArrayOutputStream();
} else {
baos.write(b);
}
}

} catch (IOException e) {
e.printStackTrace();
}
}
}


public class SoloServerSocketThread implements Runnable{
private Integer port;
private boolean isExit = false;
private ServerSocket server;

private static HashMap<String,SoloClientSocketThread> clients = new HashMap<>();
public void exit(){
isExit=true;
}

public static boolean drop(SoloClientSocketThread client){
return clients.remove(client.getClient().getInetAddress().getHostName(),client);
}

public static void drop(String clientHost){
clients.remove(clientHost);
}

public HashMap<String, SoloClientSocketThread> getClients() {
return clients;
}

public SoloServerSocketThread(Integer port) throws IOException {
this.port=port;
server = new ServerSocket(port);

}

@Override
public void run() {
try {
while (true){
Socket client = server.accept();
SoloClientSocketThread soloClient = new SoloClientSocketThread(client);
String clientHost;
if((clients.get(clientHost = soloClient.getClient().getInetAddress().getHostName()))==null) {
clients.put(clientHost,soloClient);
} else {
clients.replace(clientHost,soloClient);
}
new Thread(new SoloClientSocketThread(client)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}

public void setPort(Integer port) {
this.port=port;
}

public Integer getPort() {
return port;
}
}
...全文

相关推荐

linux 下的shell socket实现聊天室

管道实现socket,资源资源包含服务器端和客服端。

buptdpy

Linux下C语言实现聊天室:从socket到粘包处理的实战指南

网络编程是后端开发的核心技能,理解底层原理方能应对复杂的线上问题。Linux作为服务器端主流平台,其socket、多线程、I/O复用等机制构成了所有高并发框架的基石。通过一个经典的C语言聊天室项目,可以深入实践TCP/IP协议、消息分发、粘包与半包处理等关键问题。这种最小化工程实践覆盖了从socket初始化到广播消息的完整链路,并涉及gdb调试、valgrind内存检测等实用工具。无论完成课程设计还是备战技术面试,掌握这些基础都能为后续学习Java NIO或Go netpoller提供坚实支撑。聊天室虽小,

weixin_34032621

使用Socket和ServerSocket实现多人聊天的聊天室程序

基于TCP的网络编程,使用Socket和ServerSocket实现多人聊天的聊天室程序,Java网络编程章节训练的小程序

大数据-98k

Python socket实现简单聊天室

本文实例为大家分享了Python socket实现简单聊天室的具体代码,供大家参考,具体内容如下 服务端使用了select模块,实现了对多个socket的监控。客户端由于select在Windows下只能对socket使用,所以使用了多线程来实现对客户端输入和socket连接的同时监控。注意这里的socket设置为了非阻塞。这样就实现了在一个线程中同时进行socket的接收和发送。 服务器代码: # -*- coding: utf-8 -*- import socket,select connection_list = [] host = '' port = 10001 def board_

weixin_38607195

Python基于Socket实现简单聊天室

本文实例为大家分享了Python基于Socket实现简单聊天室,供大家参考,具体内容如下 服务端 #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/7/27 15:34 # @File : Server.py """ 聊天室服务端 """ import socket,select\nhost='' port=7799 addr=(host,port) inputs=[] members={} #配置服务端 def start_Server(): server=socket.socket(socket.AF_INET

weixin_38702844
评论 2
收藏 已收藏
分享
返回顶部
qq_36172692
Web 开发 81,107 成员 341,720 内容