websocket通讯客户端服务端测试样例

websocket笔记:测试代码。javascript

使用到jar:html

javaee-api-7.0.jar
tyrus-standalone-client-1.13.1.jarjava

server 端:web

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/websocket",encoders = EncoderConvert.class)
public class WebSocketServer {
    /**
     * 与某个客户端的链接会话,须要经过它来给客户端发送数据
     */
    private Session session;
    /**
     * 静态变量,用来记录当前在线链接数。应该把它设计成线程安全的
     *
     */
    private static int onlineCount = 0;
    /**
     * concurrent包的线程安全Set,用来存放每一个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通讯的话,能够使用Map来存放,其中Key能够为用户标识*
     */
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
    /**
     * 链接创建成功调用的方法
     * @param session  可选的参数。session为与某个客户端的链接会话,须要经过它来给客户端发送数据
     * @throws Exception
     */
    @OnOpen
    public void onOpen(Session session) throws Exception{
        this.session = session;
        webSocketSet.add(this);
        WebSocketMapUtil.put(this.session.getId(),this);
        addOnlineCount();           //在线数加1
        System.out.println("有新链接加入!当前在线人数为" + getOnlineCount());
    }

    /**
     * 链接关闭调用的方法
     * @throws Exception
     */
    @OnClose
    public void onClose() throws Exception{
        //从中删除
        webSocketSet.remove(this);
        WebSocketMapUtil.remove(this.session.getId());
        subOnlineCount();           //在线数减1
        System.out.println("有一链接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     * @throws IOException
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException, EncodeException {
        System.out.println("来自客户端的消息:" + message);
        for(WebSocketServer item: webSocketSet){
            try {
                //查询Service
//                String msg = "{title: '消息通知',text: '"+ message +"'}";
                item.sendMessage(new Msg("消息通知", message));
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }

    /**
     * 发生错误时调用
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error){
        System.out.println("发生错误");
        error.printStackTrace();
    }


    /**
     * 发送消息方法。
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException{
        this.session.getBasicRemote().sendText(message);
    }
    /**
     * 发送消息方法。
     * @param message
     * @throws IOException
     */
    public void sendMessage(Object message) throws IOException, EncodeException {
        this.session.getBasicRemote().sendObject(message);
    }

    /**
     * 群发消息方法。
     * @param message
     * @throws IOException
     */
    public void sendMessageAll(String message) throws IOException{
        for(WebSocketServer item: webSocketSet){
            try {
                //查询Service
                String msg = "{title: '消息通知',text: '"+ message +"'}";
                item.sendMessage(msg);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
EncoderConvert 编码转换:
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;


public class EncoderConvert implements Encoder.Text<Msg> {

    @Override
    public void init(EndpointConfig endpointConfig) {

    }

    @Override
    public void destroy() {

    }
    @Override
    public String encode(Msg msg) {
        return JSON.toJSONString(msg, new SerializerFeature[]{SerializerFeature.WriteDateUseDateFormat});
    }

}
Msg 消息:
public class Msg {
    /**
     * 消息名称
     */
    private String title;
    /**
     * 消息内容
     */
    private String text;

    public Msg() {
    }

    public Msg(String title, String text) {
        this.title = title;
        this.text = text;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}

WebSocketMapUtil json

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;


public class WebSocketMapUtil {
    public static ConcurrentMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    public static void put(String key, WebSocketServer myWebSocket){
        webSocketMap.put(key, myWebSocket);
    }

    public static WebSocketServer get(String key){
        return webSocketMap.get(key);
    }

    public static void remove(String key){
        webSocketMap.remove(key);
    }

    public static Collection<WebSocketServer> getValues(){
        return webSocketMap.values();
    }
}
WebSocketClient client端:能够从后台直接调用客户端访问server发消息给HTML。
import javax.websocket.ClientEndpoint;
import java.io.IOException;
import java.net.URI;

import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

@ClientEndpoint
public class WebSocketClient {
    private Session session;
    @OnOpen
    public void onOpen(Session session) throws IOException {
        this.session = session;
    }

    @OnMessage
    public void onMessage(String message) {
    }

    @OnError
    public void onError(Throwable t) {
        t.printStackTrace();
    }
    /**
     * 链接关闭调用的方法
     * @throws Exception
     */
    @OnClose
    public void onClose() throws Exception{
    }

    /**
     * 关闭连接方法
     * @throws IOException
     */
    public void closeSocket() throws IOException{
        this.session.close();
    }

    /**
     * 发送消息方法。
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException{
        this.session.getBasicRemote().sendText(message);
    }
    //启动客户端并创建连接
    public void start(String uri) {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        try {
            this.session = container.connectToServer(WebSocketClient.class, URI.create(uri));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

HTML:能够页面发送消息给server端,由server端接收并返回给页面。api

<!DOCTYPE html>
<html content="">
<head>
    <title>Java WebSocket Tomcat </title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta charset="UTF-8"/>
</head>
<body>
Welcome<br/><input id="text" type="text"/>
<button onclick="send()">send</button>
<hr/>
<button onclick="closeWebSocket()">close WebSocket Connect</button>
<hr/>
<div id="message"></div>
</body>

<script type="text/javascript">
    var websocket = null;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:9090/DzpjZjj/websocket");
    }
    else {
        alert('当前浏览器 Not support websocket')
    }

    //链接发生错误的回调方法
    websocket.onerror = function () {
        setMessageInnerHTML("WebSocket链接发生错误");
    };

    //链接成功创建的回调方法
    websocket.onopen = function () {
        setMessageInnerHTML("WebSocket链接成功");
    }

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data);
    }

    //链接关闭的回调方法
    websocket.onclose = function () {
        setMessageInnerHTML("WebSocket链接关闭");
    }

    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket链接,防止链接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //关闭WebSocket链接
    function closeWebSocket() {
        websocket.close();
    }

    //发送消息
    function send() {
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>
</html>

测试:浏览器

public class MyClientTest {
    private static WebSocketClient client = null;
    public static void main(String[] args){
        try {
            client = new WebSocketClient();
            String uri = "ws://localhost:9090/websocket";
            client.start(uri);
            for (int i = 0; i < 200000000; i++) {
                Thread.sleep(10000);
                client.sendMessage("模板消息测试:第" + i + "条。");
            }
            client.closeSocket();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}