websocket实现消息广播 java版
时间: 2023-11-14 19:04:32 浏览: 131
在Java中实现WebSocket消息广播可以使用Java-WebSocket库。下面是一个简单的示例代码:
```java
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.concurrent.CopyOnWriteArrayList;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
public class WebSocketBroadcastServer extends WebSocketServer {
private Collection<WebSocket> clients;
public WebSocketBroadcastServer(int port) throws UnknownHostException {
super(new InetSocketAddress(port));
clients = new CopyOnWriteArrayList<>();
}
@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
clients.add(conn);
System.out.println("New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
}
@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
clients.remove(conn);
System.out.println("Closed connection to " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
}
@Override
public void onMessage(WebSocket conn, String message) {
System.out.println("Received message: " + message);
broadcast(message);
}
@Override
public void onError(WebSocket conn, Exception ex) {
System.err.println("Error occurred on connection " + conn.getRemoteSocketAddress().getAddress().getHostAddress() + ": " + ex);
}
private void broadcast(String message) {
for (WebSocket client : clients) {
client.send(message);
}
System.out.println("Message broadcasted to " + clients.size() + " clients");
}
public static void main(String[] args) throws UnknownHostException {
int port = 8080;
WebSocketBroadcastServer server = new WebSocketBroadcastServer(port);
server.start();
System.out.println("WebSocket server started on port " + port);
}
}
```
这个示例代码创建了一个WebSocket服务器,监听指定端口(8080)。当有新连接加入时,它将追踪所有连接的客户端,并在收到消息时将消息广播给所有客户端。
你可以根据自己的需求修改和扩展这个示例代码。
阅读全文