Java中websocket使用代码示例
时间: 2024-04-29 08:21:18 浏览: 124
Java版websocket示例
以下是一个简单的Java WebSocket示例代码:
Server端:
```
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
@ServerEndpoint("/echo")
public class EchoServer {
@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(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());
}
}
```
Client端:
```
import javax.websocket.*;
import java.io.IOException;
import java.net.URI;
import java.util.Scanner;
@ClientEndpoint
public class EchoClient {
private Session session;
@OnOpen
public void onOpen(Session session) {
System.out.println("WebSocket opened: " + session.getId());
this.session = session;
}
@OnMessage
public void onMessage(String message) {
System.out.println("Message 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());
}
public void send(String message) throws IOException {
session.getBasicRemote().sendText(message);
}
public static void main(String[] args) throws Exception {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
Session session = container.connectToServer(EchoClient.class, URI.create("ws://localhost:8080/echo"));
EchoClient client = (EchoClient) session.getUserProperties().get("client");
Scanner scanner = new Scanner(System.in);
while (true) {
String message = scanner.nextLine();
client.send(message);
}
}
}
```
这个示例中定义了一个简单的WebSocket服务端和客户端,服务端接收客户端发送的消息并返回相同的消息,客户端可以发送消息到服务端。使用Java WebSocket API非常简单,只需要使用注解标记需要处理的方法即可。在服务端,@ServerEndpoint注解标记WebSocket的URI,@OnOpen、@OnMessage、@OnClose和@OnError注解分别标记WebSocket的生命周期、接收消息、关闭WebSocket和处理错误的方法。在客户端,@ClientEndpoint注解标记WebSocket的URI,注解中的URI可以是Web服务的URL或WebSocket的URL。使用WebSocketContainer.connectToServer方法连接到WebSocket服务器并获取Session对象,然后使用Session.getBasicRemote().sendText方法发送消息。
以上代码仅供参考,实际应用中可能需要更多的细节处理和异常处理。
阅读全文