工具类
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import com.wolong.rtmp.Constants;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
public class WebClient extends WebSocketClient {
private static WebClient mWebClient;
private static String mWebMsg;
/**
* 路径为ws+服务器地址+服务器端设置的子路径+参数(这里对应服务器端机器编号为参数)
* 如果服务器端为https的,则前缀的ws则变为wss
*/
private static final String mAddress = "ws://192.168.2.11:8080/socketServer/websocket";
public WebClient(URI uri) {
super(uri);
}
@Override
public void onOpen(ServerHandshake serverHandshake) {
}
@Override
public void onMessage(String s) {
mWebMsg = s;
}
@Override
public void onClose(int i, String s, boolean b) {
if(mWebClient != null){
mWebClient.close();
}
}
@Override
public void onError(Exception e) {
e.printStackTrace();
}
public static WebClient getInstance() {
if (mWebClient == null) {
synchronized (WebClient.class) {
if (mWebClient == null) {
try {
mWebClient = new WebClient(new URI(mAddress));
}catch (Exception e){
e.printStackTrace();
}
}
}
}
return mWebClient;
}
/**
* 初始化
*/
public static void initWebSocket(final String username){
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
try {
mUserName = username;
mWebClient = new WebClient(new URI(mAddress));
boolean flag = mWebClient.connectBlocking();
Log.d("msg","连接:"+flag);
} catch (Exception e) {
e.printStackTrace();
}
Looper.loop();
}
}).start();
}
MainActivity.java
WebClient.initWebSocket();//启动
WebClient.getInstance().send();//send消息