写个简单的java程序体现websocket的功能
时间: 2024-03-21 20:16:04 浏览: 44
以下是一个简单的Java程序,它使用WebSocket协议进行通信:
```java
import java.net.URI;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
public class WebSocketExample extends WebSocketClient {
public WebSocketExample(URI serverUri, Draft draft) {
super(serverUri, draft);
}
@Override
public void onOpen(ServerHandshake handshakedata) {
System.out.println("WebSocket opened: " + handshakedata.getHttpStatus() + " " + handshakedata.getHttpStatusMessage());
}
@Override
public void onMessage(String message) {
System.out.println("WebSocket message received: " + message);
}
@Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("WebSocket closed: " + code + " " + reason);
}
@Override
public void onError(Exception ex) {
System.out.println("WebSocket error: " + ex.getMessage());
}
public static void main(String[] args) throws Exception {
URI serverUri = new URI("wss://echo.websocket.org");
Draft draft = new Draft_6455();
WebSocketExample client = new WebSocketExample(serverUri, draft);
client.connect();
client.send("Hello, WebSocket!");
Thread.sleep(1000);
client.close();
}
}
```
此程序通过连接到wss://echo.websocket.org,向服务器发送一条消息,然后等待接收到服务器返回的相同消息。它使用Java-WebSocket库来实现WebSocket客户端。在WebSocketExample类中,我们覆盖了WebSocketClient类中的四个方法:onOpen,onMessage,onClose和onError。onOpen方法在WebSocket连接建立时被调用,onMessage方法在客户端收到服务器发送的消息时被调用,onClose方法在WebSocket连接关闭时被调用,onError方法在发生错误时被调用。在main方法中,我们创建了WebSocketExample对象,连接到服务器,发送一条消息,等待1秒钟,然后关闭WebSocket连接。
阅读全文