1.pom中引入依赖
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.4</version>
</dependency>
2.测试代码
import org.apache.commons.io.FileUtils;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ServerHandshake;
import org.java_websocket.drafts.Draft_6455;
import java.io.File;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
public class Testwebsocket extends WebSocketClient {
//不带cookie认证
public Testwebsocket(URI serverUri , Draft draft ) {
super( serverUri, draft );
}
public Testwebsocket( URI serverURI ) {
super( serverURI );
}
//带cookie认证时,用map
public Testwebsocket(URI serverUri, Draft draft, Map<String, String> headers, int timeout) {
super( serverUri, draft, headers, timeout );
}
@Override
public void onOpen( ServerHandshake handshakedata ) {
System.out.println( "开流--opened connection" );
}
@Override
public void onMessage( String message ) {
System.out.println( "接收--received: " + message );
}
@Override
public void onFragment( Framedata fragment ) {
System.out.println( "片段--received fragment: " + new String( fragment.getPayloadData().array() ) );
}
@Override
public void onClose( int code, String reason, boolean remote ) {
System.out.println( "关流--Connection closed by " + ( remote ? "remote peer" : "us" ) );
}
@Override
public void onError( Exception ex ) {
ex.printStackTrace();
}
public static void main(String[] args) {
try {
//用来发送的json数据,我这里将它放在一个文档里读取
String input = FileUtils.readFileToString(new File("src/main/resources/test.json"), "UTF-8");
net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(input);
//需要cookie时,用map存储cookie
//Map<String, String> headers = new HashMap<String, String>();
//headers.put("Cookie", "sso.xx.com=XX.6069xx988696471cbbc074caff1f8308;");
//使用cookie时的实例,ws地址换成自己的
//Testwebsocket c = new Testwebsocket( new URI( "ws://test.xx.com:3000/dashboard/web/test/" ), new Draft_6455(), headers, 10000);
//没有cookie时
Testwebsocket c = new Testwebsocket( new URI( "ws://test.xx.com:3000/dashboard/web/test/" ), new Draft_6455());
c.connect();
while(!c.getReadyState().equals(READYSTATE.OPEN)){
Thread.sleep(10);
System.out.println("连接还没有打开!");
}
System.out.println("连接打开了!");
//c.send("测试");
c.send(jsonObject.toString()); //发送json数据
//接收数据中,时间到了手动关闭连接,否则有可能一直接收消息
Thread.sleep(15000);
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.运行结果
4.踩的坑
一开始用的草案Draft_17,结果报错:org.java_websocket.exceptions.WebsocketNotConnectedException,并提示Draft_17已过时。
于是,使用1.3.4之后版本的Draft_6455。