websocket基于java实现在线多人聊天
时间: 2023-07-18 18:04:56 浏览: 146
实现在线多人聊天可以使用Java中的WebSocket协议,以下是一个简单的示例代码:
服务端代码:
```java
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/chat")
public class ChatServer {
private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());
@OnOpen
public void onOpen(Session session) {
sessions.add(session);
}
@OnMessage
public void onMessage(String message, Session session) throws IOException {
synchronized (sessions) {
for (Session s : sessions) {
s.getBasicRemote().sendText(message);
}
}
}
@OnClose
public void onClose(Session session) {
sessions.remove(session);
}
}
```
客户端代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
@ClientEndpoint
public class ChatClient {
private static Object waitLock = new Object();
@OnOpen
public void onOpen(Session session) {
System.out.println("Connected to server");
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println(message);
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
System.out.println(String.format("Session %s close because of %s", session.getId(), closeReason));
synchronized (waitLock) {
waitLock.notify();
}
}
public static void main(String[] args) {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
String uri = "ws://localhost:8080/chat";
try {
Session session = container.connectToServer(ChatClient.class, new URI(uri));
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = "";
while (!line.equals("exit")) {
line = reader.readLine();
session.getBasicRemote().sendText(line);
}
session.close();
} catch (DeploymentException | URISyntaxException | IOException e) {
e.printStackTrace();
}
}
}
```
在本地运行服务端(如Tomcat),然后运行客户端即可进行在线多人聊天。注意修改服务端代码中的端口号和路径。
阅读全文