android websocket構建服務端

上一篇是客戶端的事情,這一篇是服務端。java

一、添加依賴android

compile "org.java-websocket:Java-WebSocket:1.4.0"複製代碼
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
保證網絡複製代碼

二、配置兩個類web

(1)ServerSocketbash

public class ServerSocket extends WebSocketServer {

    private ServerManager serverManager;

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


    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        Log.i("webSocket", "Some one Connected..............");
        this.serverManager.UserLogin("server", conn);

    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        Log.i("webSocket", "socket closing....................");
        this.serverManager.UserLeave(conn);
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        try {
            JSONObject jo = new JSONObject(message);
            String command_code = jo.getString("command_code");
//            MsgBean msgBean = new MsgBean();
//            msgBean.setCode(command_code);
//            EventBus.getDefault().post(msgBean);
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        Log.i("webSocket", "Socket Exception:" + ex.toString());
//        MsgBean msgBean = new MsgBean();
//        msgBean.setCode(20000+"");
//        EventBus.getDefault().post(msgBean);
    }

    @Override
    public void onStart() {

    }

}
複製代碼

(2)ServerManagerwebsocket

public class ServerManager {
    private ServerSocket serverSocket = null;
    private Map<WebSocket, String> userMap = new HashMap<WebSocket, String>();

    public ServerManager() {

    }

    public void UserLogin(String userName, WebSocket socket) {
        if (userName != null || socket != null) {
            userMap.put(socket, userName);
        }
    }

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

    public void AllUserLeave() {
        Set<WebSocket> ketSet = userMap.keySet();
        for (WebSocket socket : ketSet) {
            userMap.remove(socket);
            socket.close();
        }
    }

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

    public void SendMessageToUser(String userName, String message) {
        Set<WebSocket> 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) {
        Log.i("webSocket","發送消息-----------"+message);

        Set<WebSocket> 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("webSocket", "Port error...");
            return false;
        }

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

//        WebSocketImpl.DEBUG = false;
        try {
            serverSocket = new ServerSocket(this, port);
            serverSocket.start();

            Log.i("webSocket", "Start ServerSocket Success...");
            return true;
        } catch (Exception e) {
            Log.i("webSocket", "Start Failed...");
            e.printStackTrace();
            return false;
        }
    }

    public boolean Stop() {
        try {
            serverSocket.stop();

            Log.i("webSocket", "Stop ServerSocket Success...");
            return true;
        } catch (Exception e) {
            Log.i("webSocket", "Stop ServerSocket Failed...");
            e.printStackTrace();
            return false;
        }
    }

}
複製代碼

三、調用java-web

new ServerManager.start(port);//開啓鏈接,port端口號網絡

new ServerManager.sendMsgToAllUser(msg);//羣發消息socket

new ServerManager.stop();//關閉鏈接 通常在destroy裏關閉,防止端口被佔用的狀況。ide

四、注意事項post

客戶端和服務端要保持在一個ip下工做,服務端的ip地址就是客戶端的ws。

相關文章
相關標籤/搜索