Java作为客户端向服务端发送消息:
首先导入maven依赖:
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.8</version>
</dependency>
1. WebSocket客户端类如下:
- excptMessage 用来接收服务端返回的消息
- 构造方法的参数是连接websocket服务端的URI
- 发送消息时调用send方法将消息发送给服务端
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
public class MyWebSocketClient extends WebSocketClient {
private String excptMessage;
public MyWebSocketClient(URI serverUri) {
super(serverUri);
excptMessage = null;
}
@Override
public void onOpen(ServerHandshake serverHandshake) {
System.out.println("连接成功!");
}
@Override
public void onMessage(String s) {
System.out.println("收到消息:" + s);
this.excptMessage = s;
}
@Override
public void onClose(int i, String s, boolean b) {
System.out.println("连接已断开!");
}
@Override
public void onError(Exception e) {
System.out.println("连接出现错误!");
}
public void sendMessage(String message){
this.send(message);
System.out.println("已发送消息:" + message);
}
public String getExcptMessage() {
if(excptMessage != null){
String message = new String(excptMessage);
excptMessage = null;
return message;
}
return null;
}
}
2. 测试类:
- 实例 WebSocketClient 对象,和服务端建立连接
- 为了防止发送消息时,抛出WebsocketNotConnectedException异常,所以要等客户端和服务端建立完连接后才可以发送消息,因此要设置一个循环来进行等待。
- 发送完消息后,如果要获取服务端的响应消息,也要进行等待,直到服务端响应给我们数据以后才可以获取消息并输出,如果不进行等待的话,可能会抛出NullPointerException异常。
public class Test {
public static void main(String[] args){
String message = null;
String data = "hi!";
try {
MyWebSocketClient client = new MyWebSocketClient(new URI("ws://127.0.0.1:9999/"));
client.connect();
while (!client.getReadyState().equals(WebSocket.READYSTATE.OPEN)) {
System.out.println("连接中···请稍后");
Thread.sleep(1000);
}
client.send(data);
while((message = client.getExcptMessage())==null){
System.out.println("服务忙等待...");
Thread.sleep(1000);
}
System.out.println("成功获取数据:" + message);
client.close();
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return message;
}
}