whyclj
2020-04-25 5d40a22a146008b44e46ca651f86658bd764f7d7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<!DOCTYPE html>
 
<html>
 
<head>
 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
 
    <title>websocket</title>
 
    <script type="text/javascript" src="http://cdn.bootcss.com/jquery/3.1.0/jquery.min.js"></script>
 
    <script type="text/javascript" src="http://cdn.bootcss.com/sockjs-client/1.1.1/sockjs.js"></script>
 
    <script type="text/javascript">
 
        var websocket = null;
 
        if ('WebSocket' in window) {
 
            websocket = new WebSocket("ws://localhost:8080/webSockTest/websocket");
 
        } else if ('MozWebSocket' in window) {
 
            websocket = new MozWebSocket("ws://localhost:8080/webSockTest/websocket");
 
        } else {
 
            websocket = new SockJS("http://localhost:8080/sockjs/server");
 
        }
 
        websocket.onopen = onOpen;
 
        websocket.onmessage = onMessage;
 
        websocket.onerror = onError;
 
        websocket.onclose = onClose;
 
 
        function onOpen(event) {
 
            alert(event.type);
 
        }
 
 
        function onMessage(messageEvent) {
 
            alert(messageEvent.data);
 
        }
 
 
        function onError(event) {
 
        }
 
 
        function onClose(closeEvent) {
 
            alert(closeEvent.reason);
 
        }
 
 
        function doSendUser() {
 
            if (websocket.readyState === websocket.OPEN) {
 
                var msg = document.getElementById("inputMsg").value;
 
                websocket.send(msg);//发送消息
 
                alert("发送成功!");
 
            } else {
 
                alert("连接失败!");
 
            }
 
        }
 
        window.close = function () {
 
            websocket.onclose();
 
        };
 
        function websocketClose() {
 
            websocket.close();
 
            alert("连接关闭");
 
        }
 
    </script>
 
</head>
 
<body>
 
请输入:<input id="inputMsg" name="inputMsg"/>
 
<button οnclick="doSendUser();">发送</button>
 
<button οnclick="websocketClose();">关闭连接</button>
 
</body>
 
</html>