java使用websocket
时间: 2023-11-06 16:05:25 浏览: 98
java使用websocket,并且获取HttpSession 源码分析(推荐)
Java可以使用Java API for WebSocket(JSR 356)来实现WebSocket通信。下面是一个简单的示例:
首先,需要创建一个Endpoint类来处理WebSocket连接:
```java
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
@ServerEndpoint("/websocket")
public class MyEndpoint {
@OnOpen
public void onOpen(Session session) {
System.out.println("WebSocket opened: " + session.getId());
}
@OnMessage
public void onMessage(String message, Session session) throws IOException {
System.out.println("Message received: " + message);
session.getBasicRemote().sendText("Received: " + message);
}
@OnClose
public void onClose(Session session) {
System.out.println("WebSocket closed: " + session.getId());
}
@OnError
public void onError(Throwable t) {
System.out.println("WebSocket error: " + t.getMessage());
}
}
```
然后,在应用程序中启动WebSocket服务器:
```java
import javax.websocket.server.ServerEndpointConfig;
import org.glassfish.tyrus.server.Server;
public class MyServer {
public static void main(String[] args) {
Server server = new Server("localhost", 8080, "/myapp", null, MyEndpoint.class);
try {
server.start();
System.out.println("WebSocket server started");
Thread.currentThread().join();
} catch (Exception e) {
e.printStackTrace();
} finally {
server.stop();
}
}
}
```
现在,可以使用WebSocket客户端连接到服务器:
```javascript
var ws = new WebSocket("ws://localhost:8080/myapp/websocket");
ws.onopen = function() {
console.log("WebSocket opened");
ws.send("Hello, server!");
};
ws.onmessage = function(event) {
console.log("Message received: " + event.data);
};
ws.onclose = function() {
console.log("WebSocket closed");
};
```
阅读全文