生成websocket 的java代码
时间: 2023-09-30 13:10:05 浏览: 95
以下是一个简单的Java WebSocket服务器的示例代码:
```
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
public class MyWebSocketServer extends WebSocketServer {
private static int port = 8887;
private Set<WebSocket> connections = new HashSet<>();
public MyWebSocketServer() {
super(new InetSocketAddress(port));
}
public static void main(String[] args) {
MyWebSocketServer server = new MyWebSocketServer();
server.run();
}
@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
System.out.println("New connection from " + conn.getRemoteSocketAddress());
connections.add(conn);
}
@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
System.out.println("Closed connection to " + conn.getRemoteSocketAddress() + " with exit code " + code + " additional info: " + reason);
connections.remove(conn);
}
@Override
public void onMessage(WebSocket conn, String message) {
System.out.println("Received message from " + conn.getRemoteSocketAddress() + ": " + message);
// Handle the message here
}
@Override
public void onError(WebSocket conn, Exception ex) {
System.err.println("An error occurred on connection " + conn.getRemoteSocketAddress() + ":" + ex);
}
@Override
public void onStart() {
System.out.println("WebSocket server started on port " + getPort());
}
}
```
这个WebSocket服务器使用了Java的标准库HttpServer和Java-WebSocket库。在这个例子中,我们创建了一个WebSocketServer类,并重写了它的几个方法来处理WebSocket连接的事件。在onOpen()方法中,我们将新连接添加到connections集合中。在onClose()方法中,我们从connections集合中删除连接。在onMessage()方法中,我们处理从连接接收到的消息。在onError()方法中,我们打印出发生错误的连接和异常信息。最后,在onStart()方法中,我们打印出WebSocket服务器已经启动并监听的端口号。
注意:为了运行这个WebSocket服务器,需要在Classpath中添加Java-WebSocket和HttpServer库的JAR文件。
阅读全文