公司的项目是直播相关,很自然的就会有直播间以及聊天的功能,和不少直播一样,我们也选择了环信,环信的接入和使用相对来说挺方便的,但是随着直播间人数的增多,出现了一个很严重的问题,我们称之为异次元,进入直播间看不到别人的互动,自己玩的不亦乐乎,别人也看不到…
考虑到问题的严重性,我们决定换一种方式:webSocket.
因为是做直播中即时通讯,因此消息的发送将会非常频繁,如果采取http请求,那发送每一条消息,将会新建一个链接并发送,这无疑是致命的,而webSocket是一种新的协议,长连接,一次连接成功后,即可多次发送消息,退出直播间时将连接断开即可,具体可以看这篇文章WebSocket 是什么原理?为什么可以实现持久连接?.
compile “org.java-websocket:Java-WebSocket:1.3.0”
public class XZMsgClient extends WebSocketClient{
public XZMsgClient(URI serverURI ) {
super( serverURI, new Draft_17());
}
public void sendMsg(String text) throws NotYetConnectedException {
//write a message
send(text);
}
@Override
public void onOpen( ServerHandshake handshakedata ) {
System.out.println( "opened connection" );
// if you plan to refuse connection based on ip or httpfields overload: onWebsocketHandshakeReceivedAsClient
}
@Override
public void onMessage( String message ) {
message.matches("/^id: (.*)\n(content-type: (.*)\n)?\n/m");
}
/* @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 ) {
// The codecodes are documented in class org.java_websocket.framing.CloseFrame
System.out.println( "Connection closed by " + ( remote ? "remote peer" : "us" ) );
}
@Override
public void onError( Exception ex ) {
ex.printStackTrace();
// if the error is fatal then onClose will be called additionally
}
}
/**
* 创建websocket连接
*/
private void createWebSocket() {
xzMsgClient = new XZMsgClient(uri) {
@Override
public void onOpen(ServerHandshake handshakedata) {
super.onOpen(handshakedata);
Log.i("Websocket", "Opened");
if (mUser != null) {
String messageContent = "欢迎 " + mUser.usernickname + " 进入直播间";
String msg = getJsonMessage(messageContent, Enter_OR_LEAVE, "", "1");
xzClientSendMessage(msg);
}
}
@Override
public void onMessage(String message) {
super.onMessage(message);
Log.e(TAG, "onMessage: 收到新消息 " + message);
mHandler.post(new Runnable() {
@Override
public void run() {
//处理消息
dealMessage(message);
}
});
}
@Override
public void onClose(int code, String reason, boolean remote) {
super.onClose(code, reason, remote);
Log.i("Websocket", "Closed " + reason);
}
@Override
public void onError(Exception ex) {
super.onError(ex);
Log.i("Websocket", "Error " + ex.getMessage());
}
};
xzMsgClient.connect();
}
进入直播后,即可调用sendMsg()来发送消息,为保证严谨性,可在发送消息前确定连接成功,
xzMsgClient.getReadyState().equals(WebSocket.READYSTATE.OPEN)
聊天界面销毁时,将webSocket连接断开即可
参考文章:
1.Java-WebSocket
2.websocket实现android消息推送
3.Android中脱离WebView使用WebSocket实现群聊和推送功能