java对于websocket的demo
时间: 2023-05-12 13:06:04 浏览: 119
Java对于WebSocket的Demo可以参考以下代码:
```java
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Scanner;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
public class WebSocketDemo {
public static void main(String[] args) throws URISyntaxException {
WebSocketClient client = new WebSocketClient(new URI("ws://localhost:8888")) {
@Override
public void onOpen(ServerHandshake handshakedata) {
System.out.println("Connected to server");
}
@Override
public void onMessage(String message) {
System.out.println("Received message: " + message);
}
@Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("Connection closed");
}
@Override
public void onError(Exception ex) {
ex.printStackTrace();
}
};
client.connect();
Scanner scanner = new Scanner(System.in);
while (true) {
String input = scanner.nextLine();
if (input.equals("exit")) {
client.close();
break;
}
client.send(input);
}
}
}
```
这是一个简单的Java WebSocket客户端,它连接到本地主机的8888端口,并等待用户输入消息。当用户输入消息时,它将消息发送到服务器,并在收到来自服务器的消息时打印它们。用户可以通过输入“exit”来关闭客户端。
阅读全文