写一段完整的java发送和接收websocket的代码
时间: 2024-05-13 13:21:07 浏览: 107
以下是一个完整的Java发送和接收WebSocket的代码示例:
发送WebSocket消息:
```
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
public class WebSocketSender {
public static void main(String[] args) throws URISyntaxException, InterruptedException {
WebSocketClient client = new WebSocketClient(new URI("wss://echo.websocket.org/")) {
@Override
public void onOpen(ServerHandshake handshakedata) {
System.out.println("WebSocket opened");
}
@Override
public void onMessage(String message) {
System.out.println("Received message: " + message);
}
@Override
public void onError(Exception ex) {
System.err.println("WebSocket error: " + ex.getMessage());
}
@Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("WebSocket closed: " + reason);
}
};
client.connectBlocking();
// Send text message
client.send("Hello, WebSocket!");
// Send binary message
byte[] data = "Hello, WebSocket!".getBytes(StandardCharsets.UTF_8);
ByteBuffer buffer = ByteBuffer.wrap(data);
client.send(buffer);
// Wait for messages to be sent and received
Thread.sleep(5000);
client.close();
}
}
```
接收WebSocket消息:
```
import java.net.InetSocketAddress;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
public class WebSocketReceiver extends WebSocketServer {
public WebSocketReceiver(int port) {
super(new InetSocketAddress(port));
}
@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
System.out.println("WebSocket opened");
}
@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
System.out.println("WebSocket closed: " + reason);
}
@Override
public void onMessage(WebSocket conn, String message) {
System.out.println("Received text message: " + message);
}
@Override
public void onMessage(WebSocket conn, ByteBuffer message) {
System.out.println("Received binary message: " + new String(message.array()));
}
@Override
public void onError(WebSocket conn, Exception ex) {
System.err.println("WebSocket error: " + ex.getMessage());
}
public static void main(String[] args) throws InterruptedException {
WebSocketReceiver server = new WebSocketReceiver(8887);
server.start();
// Wait for messages to be received
Thread.sleep(5000);
server.stop();
}
}
```
这两个类分别表示WebSocket的发送端和接收端,可以通过不同的端口号来启动多个接收端实例。启动这两个类后,发送端会向接收端发送两条消息,一条是文本消息,一条是二进制消息。接收端收到消息后会打印出来。发送端和接收端都在收到消息后等待5秒后关闭WebSocket连接。
阅读全文