创建websocket的java代码
时间: 2023-09-02 21:14:19 浏览: 80
以下是使用Java创建WebSocket服务器的示例代码:
```java
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
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 {
public MyWebSocketServer(int port) {
super(new InetSocketAddress(port));
}
@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
System.out.println("New connection from " + conn.getRemoteSocketAddress());
}
@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
System.out.println("Closed connection to " + conn.getRemoteSocketAddress() + " with code " + code + " and reason " + reason);
}
@Override
public void onMessage(WebSocket conn, String message) {
System.out.println("Received message from " + conn.getRemoteSocketAddress() + ": " + message);
conn.send("Server received message: " + message);
}
@Override
public void onError(WebSocket conn, Exception ex) {
System.err.println("Error occurred on connection to " + conn.getRemoteSocketAddress());
ex.printStackTrace();
}
public static void main(String[] args) throws Exception {
final int port = 8888;
MyWebSocketServer server = new MyWebSocketServer(port);
server.start();
System.out.println("WebSocket server started on port " + server.getPort());
HttpServer httpServer = HttpServer.create(new InetSocketAddress(port + 1), 0);
httpServer.createContext("/", new HttpHandler() {
@Override
public void handle(HttpExchange exchange) throws IOException {
String response = "WebSocket server is running on port " + port;
exchange.sendResponseHeaders(200, response.length());
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
});
httpServer.setExecutor(Executors.newCachedThreadPool());
httpServer.start();
System.out.println("HTTP server started on port " + (port + 1));
}
}
```
这个简单的WebSocket服务器使用了java-websocket库。它监听指定的端口,并在收到消息时回复相同的消息。还有一个HTTP服务器,可以使用浏览器或其他HTTP客户端访问,以确认WebSocket服务器正在运行。
阅读全文