JAVA实现websocket

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhouchenxuan/article/details/71473863

什么是websocket?

传统的通讯模式是这样的:客户端(浏览器等)主动向服务器发送一个请求,服务器接收之后,处理这个请求,然后返回一个响应给客户端。大多数都是客户端向服务器发送请求,而服务器很难主动向客户端发送数据。

websocket实现了浏览器与服务器的全双工通信,使服务端也能主动向客户端发送数据。

websocket工作流程是这样的:客户端向服务器发出建立websocket连接的请求,在websocket连接建立之后,客户端和服务端就可以通过TCP连接传输数据。

如果在tomcat上部署的话,需要保证版本在Tomcat7.0.47以上。

  • index.jsp
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){
    var websocket = null;

    //判断浏览器是否支持websocket
    if('WebSocket' in window) {
        //如果支持,创建websocket对象,注意url格式
        websocket = new WebSocket('ws://localhost:8080/zhouchenxuan/go');
    }else {
        alert('浏览器版本不支持websocket!');
    }

    //定义连接错误的回调方法
    websocket.onerror = function() {
        alert('websocket连接出错!');
    }

    //定义连接成功的回调方法
    websocket.onopen = function() {
        alert('websocket连接成功!');
    }

    //定义websocket关闭的回调方法
    websocket.onclose = function() {
        alert('websocket已关闭!')
    }

    //当窗口关闭时,主动去关闭websocket连接
    window.onbeforeunload = function() {
        closeWebSocket();
    }

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

    $('#send').click(function() {
        websocket.send($('#input').val());
    });
});

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

function handleMsg(msg) {
    $('#msg').append(msg + '\n');
}
</script>
<body>
    <input name="input" id="input" type="text" />&nbsp;<input name="send" id="send" type="button" value="发送请求" />
    <br><hr style="width:50%;" align="left">
    <textarea name="msg" id="msg" style="width: 260px;height:190px"></textarea>
</body>
  • Test.java
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;



/**
 * 将目前的类定义成一个websocket服务器端
 */
@ServerEndpoint("/go")
public class Test {

    //concurrent包的线程安全Set,用来存放每个客户端对应的Test对象。
    private static CopyOnWriteArraySet<Test> set = new CopyOnWriteArraySet<Test>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    /**
     * 连接建立成功调用的方法
     * @param session
     */
    @OnOpen
    public void OnOpen(Session session) {
        this.session = session;
        set.add(this);
        System.out.println("OnOpen()方法被执行...");
        System.out.println("websocket连接建立成功...");
        System.out.println();
    }

    /**
     * 连接关闭的方法
     */
    @OnClose
    public void OnClose() {
        set.remove(this);
        System.out.println("OnClose()方法被执行...");
        System.out.println("websocket连接已经关闭...");
        System.out.println();
    }

    /**
     * 接收消息的方法
     * @param msg
     * @param session
     */
    @OnMessage
    public void OnMessage(String msg, Session session) {
        System.out.println("已从客户端接收消息:" + msg);

        //可以做一些复杂逻辑,这里每秒中发送一条数据
        for(int i = 0;i < 10;i++) {
            try {
                Thread.currentThread().sleep(1000);
                //向所有客户端发消息
                for(Test t : set) {
                    t.sendResponse("这是第" + (i + 1) + "条信息...");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("向客户端发送数据完毕...");
    }

    /**
     * 出错的方法,注意参数不能错
     * @param session
     * @param error
     */
    @OnError
    public void OnError(Session session, Throwable error) {
        System.out.println("OnError()方法被执行...");
        System.out.println("websocket出错...");
        System.out.println();
    }

    //发送数据到客户端,这个没有注解
    public void sendResponse(String str) {
        try {
            System.out.println("sendResponse()方法被执行...");
            this.session.getBasicRemote().sendText(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

代码复制完了,我们打开浏览器跑一下试试。。。
进入到测试页面,会提示“连接成功…”
这里写图片描述

输入一些信息,然后点击“发送请求”,后台就会接收信息,也会把服务器的信息发送到浏览器。
这里写图片描述

猜你喜欢

转载自blog.csdn.net/zhouchenxuan/article/details/71473863