Java WebSocket服务端实现

在线调试工具

http://www.blue-zero.com/websocket/

添加JAR文件

java-websocket-1.3.0.jar

编写ServerSocket.java

package com.wei.socket;

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

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

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 onClose(WebSocket socket, int message,
            String reason, boolean remote) {
        _serverManager.UserLeave(socket);
    }

    @Override
    public void onError(WebSocket socket, Exception message) {
        System.out.println("Socket Exception:"+message.toString());
    }

    @Override
    public void onMessage(WebSocket socket, String message) {
        System.out.println("OnMessage:"+message.toString());

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

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

    @Override
    public void onOpen(WebSocket socket, ClientHandshake handshake) {
        System.out.println("Some one Connected...");
    }

}

编写ServerManager.java

package com.wei.socket;

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

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

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);
            System.out.println("LOGIN:"+userName);

            SendMessageToAll(userName+"...Login...");
        }
    }

    public void UserLeave(WebSocket socket){
        if (userMap.containsKey(socket)) {
            String userName=userMap.get(socket);
            System.out.println("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) {
            System.out.println("Port error...");
            return false;
        }

        System.out.println("Start ServerSocket...");

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

    public boolean Stop(){
        try {
            serverSocket.stop();
            System.out.println("Stop ServerSocket Success...");
            return true;
        } catch (Exception e) {
            System.out.println("Stop ServerSocket Failed...");
            e.printStackTrace();
            return false;
        }
    }

}

编写主函数

import java.util.Scanner;

import com.wei.socket.ServerManager;

public class Test {

    public static void main(String[] args) {

        ServerManager serverManager=new ServerManager();

        boolean isRun=true;
        Scanner scanner=new Scanner(System.in);

        System.out.println("Input your choice:");
        while(isRun){
            int input=scanner.nextInt();
            switch (input) {
            case 1:
                serverManager.Start(8888);
                break;
            case 2:
                serverManager.Stop();
                isRun=false;
                break;
            default:
                break;
            }
        }
    }

}

你可能感兴趣的:(Java)