Android搭建WebSocket服务端

WebSocket简介

WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端。全双工就是指客户端和服务端可以同时进行双向通信,强调同时、双向通信。

我个人对WebSocket的印象还停留在上大学的时候,出来工作之后一直没用到过,这次项目中需求是Android搭建WebSocket服务端,所以才不得不重新去学习了解一下WebSocket,查了很多资料,基本上移动端做WebSocket都是作为客户端的应用场景,很少有作为服务端的,然后我试着去看了下Java后端搭建WebSocket服务端的方法,最后搭建出一个Android WebSocket服务端,下面把代码贴出来,我对WebSocket并不是特别精通,有很多不足之处,希望大家指正出来。

compile "org.java-websocket:Java-WebSocket:1.3.6"

 

ServerSocket类

import android.util.Log;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.net.UnknownHostException;

/**
 * Created by Roc on 2018/10/9.
 */
public class ServerSocket extends WebSocketServer {

    private ServerManager _serverManager;

    public ServerSocket(ServerManager serverManager,int port) throws UnknownHostException {
        super(new InetSocketAddress(port));
        _serverManager=serverManager;
    }




    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        Log.i("TAG","Some one Connected...");
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        _serverManager.UserLeave(conn);
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        Log.i("TAG","OnMessage:"+message.toString());

        if (message.equals("1")) {
            _serverManager.SendMessageToUser(conn, "What?");
        }

        String[] result=message.split(":");
        if (result.length==2) {
            if (result[0].equals("user")) {
                _serverManager.UserLogin(result[1], conn);
            }
        }
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        Log.i("TAG","Socket Exception:"+ex.toString());
    }

    @Override
    public void onStart() {

    }
}
ServerManager类
import android.util.Log;

import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketImpl;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by Roc on 2018/10/9.
 */
public class ServerManager {
    private ServerSocket serverSocket=null;
    private Map userMap=new HashMap();

    public ServerManager(){

    }

    public void UserLogin(String userName,WebSocket socket){
        if (userName!=null||socket!=null) {
            userMap.put(socket, userName);
            Log.i("TAG","LOGIN:"+userName);
            SendMessageToAll(userName+"...Login...");
        }
    }

    public void UserLeave(WebSocket socket){
        if (userMap.containsKey(socket)) {
            String userName=userMap.get(socket);
            Log.i("TAG","Leave:"+userName);
            userMap.remove(socket);
            SendMessageToAll(userName+"...Leave...");
        }
    }

    public void SendMessageToUser(WebSocket socket,String message){
        if (socket!=null) {
            socket.send(message);
        }
    }

    public void SendMessageToUser(String userName,String message){
        Set ketSet=userMap.keySet();
        for(WebSocket socket : ketSet){
            String name=userMap.get(socket);
            if (name!=null) {
                if (name.equals(userName)) {
                    socket.send(message);
                    break;
                }
            }
        }
    }

    public void SendMessageToAll(String message){
        Set ketSet=userMap.keySet();
        for(WebSocket socket : ketSet){
            String name=userMap.get(socket);
            if (name!=null) {
                socket.send(message);
            }
        }
    }

    public boolean Start(int port){

        if (port<0) {
            Log.i("TAG","Port error...");
            return false;
        }

        Log.i("TAG","Start ServerSocket...");

        WebSocketImpl.DEBUG=false;
        try {
            serverSocket=new ServerSocket(this,port);
            serverSocket.start();
            Log.i("TAG","Start ServerSocket Success...");
            return true;
        } catch (Exception e) {
            Log.i("TAG","Start Failed...");
            e.printStackTrace();
            return false;
        }
    }

    public boolean Stop(){
        try {
            serverSocket.stop();
            Log.i("TAG","Stop ServerSocket Success...");
            return true;
        } catch (Exception e) {
            Log.i("TAG","Stop ServerSocket Failed...");
            e.printStackTrace();
            return false;
        }
    }


}

使用的时候只需要用ServerManager对象调用start和stop方法,调用start方法需要设置一个端口号。搭建好了之后可以写一个客户端测试一下,下面是我测试截图,我使用的是在线测试工具进行测试(http://www.blue-zero.com/websocket/)

Android搭建WebSocket服务端_第1张图片

Android搭建WebSocket服务端_第2张图片

 

 

 

 

 

 

你可能感兴趣的:(技术,Android,WebSocket,WebSocket服务端)