java 编写 java_websocket 多个websocket 实例
时间: 2023-11-18 14:54:53 浏览: 98
Java可以使用Java-WebSocket库来编写多个WebSocket实例。在使用Java-WebSocket库时,需要创建多个WebSocketServer实例,并为每个实例指定不同的端口号。每个WebSocketServer实例都可以处理多个WebSocket连接。在处理WebSocket连接时,可以使用WebSocket类的onOpen、onClose、onMessage和onError方法来处理WebSocket连接的打开、关闭、消息和错误事件。此外,还可以使用WebSocket类的send方法向客户端发送消息。下面是一个简单的Java-WebSocket多个WebSocket实例的示例代码:
```
import java.net.InetSocketAddress;
import java.util.concurrent.CopyOnWriteArrayList;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
public class MultiWebSocketServer {
private CopyOnWriteArrayList<WebSocket> webSockets = new CopyOnWriteArrayList<>();
public MultiWebSocketServer(int... ports) {
for (int port : ports) {
WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) {
@Override
public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
webSockets.add(webSocket);
System.out.println("WebSocket opened: " + webSocket.getRemoteSocketAddress()); }
@Override
public void onClose(WebSocket webSocket, int i, String s, boolean b) {
webSockets.remove(webSocket);
System.out.println("WebSocket closed: " + webSocket.getRemoteSocketAddress());
}
@Override
public void onMessage(WebSocket webSocket, String s) {
System.out.println("WebSocket message received: " + s);
}
@Override
public void onError(WebSocket webSocket, Exception e) {
System.out.println("WebSocket error: " + e.getMessage());
}
};
server.start();
System.out.println("WebSocket server started on port " + port);
}
}
public void broadcast(String message) {
for (WebSocket webSocket : webSockets) {
webSocket.send(message);
}
}
public static void main(String[] args) {
MultiWebSocketServer server = new MultiWebSocketServer(8080, 8081);
server.broadcast("Hello, world!");
}
}
```
此代码创建了两个WebSocketServer实例,分别监听8080和8081端口。在每个WebSocketServer实例的onOpen、onClose、onMessage和onError方法中,分别处理WebSocket连接的打开、关闭、消息和错误事件。在broadcast方法中,使用WebSocket类的send方法向所有客户端发送消息。
阅读全文