使用Java写一个WebSocket的例子
时间: 2023-07-20 09:40:28 浏览: 153
好的,以下是一个使用 Java API 实现 WebSocket 的例子:
1. 创建一个类并实现 javax.websocket.Endpoint 接口
```java
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.Session;
public class MyEndpoint extends Endpoint {
@Override
public void onOpen(Session session, EndpointConfig config) {
System.out.println("WebSocket opened: " + session.getId());
// Add a message handler to the session
session.addMessageHandler(new MessageHandler.Whole<String>() {
@Override
public void onMessage(String message) {
System.out.println("Message received: " + message);
// Send a message back to the client
try {
session.getBasicRemote().sendText("Received message: " + message);
} catch (IOException e) {
e.printStackTrace();
}
}
});
// Add a binary message handler to the session
session.addMessageHandler(new MessageHandler.Whole<ByteBuffer>() {
@Override
public void onMessage(ByteBuffer message) {
System.out.println("Binary message received: " + message);
// Send a binary message back to the client
try {
session.getBasicRemote().sendBinary(message);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
@Override
public void onClose(Session session, CloseReason closeReason) {
System.out.println("WebSocket closed: " + session.getId() + " Reason: " + closeReason);
}
@Override
public void onError(Session session, Throwable throwable) {
System.out.println("WebSocket error: " + session.getId());
throwable.printStackTrace();
}
}
```
2. 使用 javax.websocket.server.ServerEndpoint 注解指定 WebSocket 的路径
```java
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/my-websocket")
public class MyWebSocketServer {
public MyWebSocketServer() {
System.out.println("WebSocket server started.");
}
}
```
3. 启动 WebSocket 服务器
```java
import javax.websocket.server.ServerContainer;
import javax.websocket.server.ServerEndpointConfig;
import org.apache.tomcat.websocket.server.Constants;
import org.apache.tomcat.websocket.server.WsSci;
public class WebSocketServerApp {
public static void main(String[] args) throws Exception {
// Start embedded Tomcat
Tomcat tomcat = new Tomcat();
tomcat.setPort(8080);
// Add WebSocket support
tomcat.addWebapp("/my-webapp", new File(".").getAbsolutePath());
tomcat.getServletContext().setExtendedListenerTypes(true);
tomcat.getServletContext().addListener(new WsSci());
// Add WebSocket endpoint
ServerContainer serverContainer =
(ServerContainer) tomcat.getServletContext().getAttribute(Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
ServerEndpointConfig serverEndpointConfig = ServerEndpointConfig.Builder.create(MyEndpoint.class, "/my-websocket").build();
serverContainer.addEndpoint(serverEndpointConfig);
// Start Tomcat
tomcat.start();
tomcat.getServer().await();
}
}
```
以上代码启动一个 WebSocket 服务器,监听在 `ws://localhost:8080/my-webapp/my-websocket` 路径,可以接收文本和二进制消息,并原样返回给客户端。
阅读全文