浏览器使用WebSocket实时通讯

2021-12-08 15:12:44 浏览数 (1)

如果你要有一个支持 WebSocket的服务器(Java、Php等),可以在浏览器中使用一个新的WebSocket服务协议,来打开一个链接:

代码语言:javascript复制
var socket = new WebSocket("ws://172.0.0.1:8080/SpringWebSocketPush/websck");  

与http://这一URL 前缀等价的WebSocket 前缀 是 ws:// ,安全 WebSocket 则有一个与http://等价的 wss:// 前缀。 该套接口对象有四个用来监听套接口事件的回调:

代码语言:javascript复制
    socket.onopen = function(){

        //打开

    }


    socket.onmessage = function(){

        //在event.data消息数据

    }

    socket.onclose = function(){

        //关闭WebSocket

    }

    socket.onerror = function(){

        //错误触发

    }

通过套接口发送数据,调用socket.send:

代码语言:javascript复制
    socket.send(message)

代码附上:

代码语言:javascript复制
<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
        <title>WebSocket</title>
    </head>

    <body>
    </body>
    <script>
        var socket;
        if (window.WebSocket) {
            socket = new WebSocket("ws://localhost:8080/myapp");
            socket.onmessage = function(event) {
                alert("Received data from websocket: "   event.data);
            }
            socket.onopen = function(event) {
                alert("Web Socket opened!");
            };
            socket.onclose = function(event) {
                alert("Web Socket closed.");
            };
        } else {
            alert("Your browser does not support Websockets. (Use Chrome)");
        }

        function send(message) {
            if (!window.WebSocket) {
                return;
            }
            if (socket.readyState == WebSocket.OPEN) {
                socket.send(message);
            } else {
                alert("The socket is not open.");
            }
        }
    </script>

</html>

0 人点赞