不废话直接上 我的java websocket源码,跑通了的
引用的jar包
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.2</version>
</dependency>
import okhttp3.*;
import okio.ByteString;
public class Client extends WebSocketListener {
public static void main(String[] args) throws Exception {
System.out.println("开始");
// 构建鉴权url
OkHttpClient client = new OkHttpClient.Builder().build();
Request request = new Request.Builder().url("ws://ip:port/xx").build();
client.newWebSocket(request, new Client());
while (true){
System.out.println("主线程休眠2s,保证进程不结束");
Thread.sleep(2000);
}
}
@Override
public void onOpen(WebSocket webSocket, Response response) {
super.onOpen(webSocket, response);
webSocket.send("hello");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
super.onMessage(webSocket, text);
System.out.println("String text="+text);
// if(true){//如果连接可以关闭了,就close
// webSocket.close(1000,"");
// }
}
@Override
public void onMessage(WebSocket webSocket, ByteString text) {
super.onMessage(webSocket, text);
System.out.println("ByteString text="+text);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
super.onFailure(webSocket, t, response);
try {
if (null != response) {
int code = response.code();
System.out.println("onFailure code:" + code);
System.out.println("onFailure body:" + response.body().string());
if (101 != code) {
System.out.println("connection failed");
System.exit(0);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}