java写一段websocket示例程序
时间: 2023-03-27 10:04:58 浏览: 170
Java版websocket示例
好的,以下是一个简单的 Java WebSocket 示例程序:
```java
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Scanner;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
@ClientEndpoint
public class WebSocketClient {
private Session session;
@OnOpen
public void onOpen(Session session) {
this.session = session;
System.out.println("Connected to server");
}
@OnMessage
public void onMessage(String message) {
System.out.println("Received message: " + message);
}
@OnClose
public void onClose(CloseReason reason) {
System.out.println("Disconnected from server: " + reason.getReasonPhrase());
}
public void sendMessage(String message) {
this.session.getAsyncRemote().sendText(message);
}
public static void main(String[] args) throws URISyntaxException {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
String uri = "ws://localhost:808/websocket";
WebSocketClient client = new WebSocketClient();
container.connectToServer(client, new URI(uri));
Scanner scanner = new Scanner(System.in);
while (true) {
String message = scanner.nextLine();
client.sendMessage(message);
}
}
}
```
这个程序使用了 Java 的 WebSocket API,通过 `@ClientEndpoint` 注解标记一个 WebSocket 客户端类,然后实现 `OnOpen`、`OnMessage` 和 `OnClose` 方法来处理连接、消息和关闭事件。在 `main` 方法中,我们使用 `WebSocketContainer` 来连接到 WebSocket 服务器,然后通过 `Scanner` 读取用户输入,并通过 `sendMessage` 方法发送消息到服务器。
阅读全文