用java写个websocket
时间: 2023-05-19 09:06:08 浏览: 119
java实现websocket
非常好的问题!下面是一个简单的Java WebSocket示例代码:
```java
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
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 static CountDownLatch latch;
private static Session session;
@OnOpen
public void onOpen(Session session) {
System.out.println("Connected to server!");
WebSocketClient.session = session;
latch.countDown();
}
@OnMessage
public void onMessage(String message) {
System.out.println("Received message: " + message);
}
@OnClose
public void onClose(CloseReason reason) {
System.out.println("Connection closed: " + reason);
}
public static void main(String[] args) throws URISyntaxException, InterruptedException {
latch = new CountDownLatch(1);
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
String uri = "ws://localhost:8080/websocket";
container.connectToServer(WebSocketClient.class, new URI(uri));
latch.await();
Scanner scanner = new Scanner(System.in);
while (true) {
String message = scanner.nextLine();
session.getBasicRemote().sendText(message);
}
}
}
```
这个示例代码使用了Java的WebSocket API来连接到一个WebSocket服务器,并在控制台上打印收到的消息。你可以将`ws://localhost:8080/websocket`替换为你想要连接的WebSocket服务器的URI。在`main`方法中,我们使用了一个`Scanner`对象来读取用户输入,并将输入的文本发送到服务器。
阅读全文