java 实现websocket客户端向服务端发送已知指令及接收服务端返回信息并打印出来
时间: 2023-11-11 12:07:56 浏览: 121
以下是利用Java实现WebSocket客户端向服务端发送已知指令及接收服务端返回信息并打印出来的代码示例:
```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 WebSocketExample extends WebSocketClient {
public WebSocketExample(URI serverUri) {
super(serverUri);
}
@Override
public void onOpen(ServerHandshake handshakedata) {
System.out.println("Connected to server: " + this.getURI());
}
@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: " + code + ", " + reason);
}
@Override
public void onError(Exception ex) {
ex.printStackTrace();
}
public static void main(String[] args) {
try {
WebSocketExample client = new WebSocketExample(new URI("ws://localhost:8080"));
client.connect();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter command to send to server: ");
String command = scanner.nextLine();
if (command.equalsIgnoreCase("exit")) {
break;
}
client.send(command);
}
scanner.close();
client.close();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
```
在该示例中,我们使用了Java-WebSocket库来实现WebSocket客户端。在WebSocketExample类中,我们覆盖了WebSocketClient的四个方法,以便在连接打开、收到消息、连接关闭或出现错误时执行相应的操作。
在main方法中,我们创建了一个WebSocketExample对象并连接到了本地的WebSocket服务器。然后,我们使用Scanner对象从控制台读取用户输入的指令,并将其发送到服务器上。当用户输入“exit”时,程序将退出。
当WebSocket服务器向客户端发送消息时,onMessage方法将被调用,并打印出收到的消息。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044736.png)
![-](https://img-home.csdnimg.cn/images/20241231044736.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)