package com.manage.service.webSocket;

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

import javax.websocket.Session;
import java.io.IOException;
import java.net.InetSocketAddress;

public class WebServer extends WebSocketServer {
	private Session session;
    public WebServer(int port) {
        super(new InetSocketAddress(port));
    }

    public WebServer(InetSocketAddress address) {
        super(address);
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        // ws连接的时候触发的代码，onOpen中我们不做任何操作
    }
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText("2");
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        //断开连接时候触发代码
        userLeave(conn);
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        if(null != message){
            String userName = message.replaceFirst("online", message);//用户名
            userJoin(conn,userName);//用户加入
        }
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        //错误时候触发的代码
        System.out.println("on error");
        ex.printStackTrace();
    }
    /**
     * 去除掉失效的websocket链接
     * @param conn
     */
    private void userLeave(WebSocket conn){
        WsPool.removeUser(conn);
    }
    /**
     * 将websocket加入用户池
     * @param conn
     * @param userName
     */
    private void userJoin(WebSocket conn,String userName){
        WsPool.addUser(userName, conn);
    }

//    public void start() {
//        if( selectorthread != null )
//            throw new IllegalStateException( getClass().getName() + " can only be started once." );
//        new Thread( this ).start();;
//    }
    
//    public static void main(String args[]){
//        WebSocketImpl.DEBUG = false;
//        int port = 8887; // 端口
//        WsServer s = new WsServer(port);
//        s.start();
//    }

    @Override
    public void onStart() {
    }
    
}
