java js实现Websocket通讯实例

本文主要介绍如何使用java实现websocket server,以及使用java、js生成websocket client进行通讯交互

1、java所需jar包


javax.websocket
javax.websocket-api
1.0


org.java-websocket
Java-WebSocket
1.3.0



2、java类server实现

import java.net.InetSocketAddress;
import java.util.List;
import java.util.Map;
import java.util.Set;


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


import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yy.ent.commons.base.valid.BlankUtil;


public class MliveWebSocket extends WebSocketServer {
    
    public static Map> socketMap = Maps.newHashMap();//频道-进入频道用户的连接列表
    
    public MliveWebSocket(InetSocketAddress address) {
        super(address);
    }
    
    /**
     * 
     * @param address
     * @param decoders用于限制websocket版本号
     */
    public MliveWebSocket(InetSocketAddress address, int decoders) {
        super(address, decoders);
    }


    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        System.out.println("onOpen");
        String desc = handshake.getResourceDescriptor().substring(1);//例如页面请求:'ws://127.0.0.1:4444/'+topSid; desc获取到的就是topSid。此处以desc区分不同分类的连接,用于后续通讯
        if(BlankUtil.isBlank(socketMap.get(desc))){
            List list = Lists.newArrayList();
            list.add(conn);//connect成功时候执行
            socketMap.put(desc, list);
        } else {
            socketMap.get(desc).add(conn);
        }
    }


    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        System.out.println("onClose");
        Set setList = socketMap.keySet();
        for (String string : setList) {
            if (socketMap.get(string).contains(conn)) {
                socketMap.get(string).remove(conn);//删除连接
                if (socketMap.get(string).isEmpty()) {//连接为空时清除
                    socketMap.remove(string);
                }
                break;
            }
        }
    }


    @Override
    public void onMessage(WebSocket conn, String message) {
        System.out.println("onMessage");
        System.out.println(message);
        /*List socketList = socketMap.get(message);
        for (WebSocket webSocket : socketList) {
            webSocket.send("已收到~");
        }*/
        sendInAllChannel("~已收到~");//测试收到信息时全局发送消息
    }


    @Override
    public void onError(WebSocket conn, Exception ex) {
        System.out.println("onError");
        Set setList = socketMap.keySet();
        for (String string : setList) {
            if (socketMap.get(string).contains(conn)) {
                socketMap.get(string).remove(conn);//删除连接
                if (socketMap.get(string).isEmpty()) {//连接为空时清除
                    socketMap.remove(string);
                }
                break;
            }
        }
    }
    
    /**
     * 服务端启动
     * @param args
     */
    public static void main(String[] args) {
        InetSocketAddress address = new InetSocketAddress(4444);
        MliveWebSocket socket = new MliveWebSocket(address);
        socket.start();//启动websocket服务器进程
    }
    
    /**
     * 发送消息到某一个连接
     * @param channel
     * @param message
     */
    public void sendInOneChannel(String channel,String message){
        List list = socketMap.get(channel);
        for (WebSocket webSocket : list) {
            webSocket.send(message);
        }
    }
    
    /**
     * 发送消息到所有连接
     * @param message
     */
    public void sendInAllChannel(String message){
        Set setList = socketMap.keySet();
        for (String string : setList) {
            List list = socketMap.get(string);
            for (WebSocket webSocket : list) {
                webSocket.send(message);
            }
        }
    }
}



3、html5 js连接java server

function svc_connectPlatform(topSid) {
var wsServer = 'ws://127.0.0.1:4444/'+topSid;
    try {
svc_websocket = new WebSocket(wsServer);
    } catch (evt) {
console.log("new WebSocket error:" + evt.data);
svc_websocket = null;
if (typeof(connCb) != "undefined" && connCb != null)
connCb("-1", "connect error!");
return;
    }
svc_websocket.onopen = svc_onOpen;
svc_websocket.onclose = svc_onClose;
svc_websocket.onmessage = svc_onMessage;
svc_websocket.onerror = svc_onError;
}


function svc_onOpen(evt) {
console.log("Connected to WebSocket server.");
}


function svc_onClose(evt) { 
console.log("Disconnected");
}


function svc_onMessage(evt) {
console.log('Retrieved data from server: ' + evt.data);
}


function svc_onError(evt) {
console.log('Error occured: ' + evt.data);
}


function svc_send(msg) {
if (svc_websocket.readyState == WebSocket.OPEN) {
svc_websocket.send(msg);
} else {
console.log("send failed. websocket not open. please check.");
}
}

4、java实现websocket客户端



import java.net.URI;
import java.nio.channels.NotYetConnectedException;


import org.java_websocket.WebSocket.READYSTATE;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;


/**
 * websocket java客户端
 * @author Administrator
 *
 */
public class MliveWebSocketClient extends WebSocketClient {


    public MliveWebSocketClient(URI serverURI) {
        super(serverURI);
        // TODO Auto-generated constructor stub
    }


    @Override
    public void onOpen(ServerHandshake handshakedata) {
        // TODO Auto-generated method stub
        System.out.println("onOpen");
    }


    @Override
    public void onMessage(String message) {
        // TODO Auto-generated method stub
        System.out.println("onMessage");
        System.out.println(message);
    }


    @Override
    public void onClose(int code, String reason, boolean remote) {
        // TODO Auto-generated method stub
        System.out.println("onClose");
    }


    @Override
    public void onError(Exception ex) {
        // TODO Auto-generated method stub
        System.out.println("onError");
    }


    public static void main(String[] args) {
        MliveWebSocketClient client = new MliveWebSocketClient(URI.create("ws://127.0.0.1:4444/1111"));
        try {
            client.connect();
            //NOT_YET_CONNECTED, CONNECTING, OPEN, CLOSING, CLOSED;连接的所有状态
            int i = 0;
            while(true){
                if(client.getReadyState() == READYSTATE.OPEN){
                    client.send("hell0");//状态为open才可以发送消息
                    break;
                } else if(client.getReadyState() != READYSTATE.CLOSED){
                    System.out.println(client.getReadyState()+""+(i++));
                    Thread.sleep(1000);
                } else {
                    break;
                }
            }
        } catch (NotYetConnectedException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


你可能感兴趣的:(java js实现Websocket通讯实例)