| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- <html>
- <head>
- <style>
- #server-info {
- width:50%;
- height:20%;
- font-size:40px;
- /* border:1px solid red; */
- }
- #textarea {
- width:100%;
- height:auto;
- /* border:1px solid red; */
- }
- /* p {color:blue} */
- </style>
- </head>
- <body>
- <div Id = 'server-info'>服务器返回信息</div>
- <div Id = 'textarea'>
- <textarea Id="textarea_id" rows="30" cols="120"></textarea>
- </div>
-
- <script>
- let str = '';
- // var ws = new WebSocket("ws://localhost:3000");
- // var ws = new WebSocket("ws://121.4.59.141:3000/node/");
- var ws = new WebSocket("ws://www.yuyekeji.cn:3000/node/");
- console.log("WebSocket建立成功");
- //申请一个WebSocket对象,参数是服务端地址,同http协议使用http://开头一样,WebSocket协议的url使用ws://开头,另外安全的WebSocket协议使用wss://开头
- ws.onopen = function () {
- //当WebSocket创建成功时,触发onopen事件
- console.log("open");
- document.getElementById("server-info").innerHTML = "已建立服务端连接!"
- ws.send('{"name":"22","type":"login","user_name":"","message":""}'); //将消息发送到服务端
- }
- ws.onmessage = function (e) {
- //当客户端收到服务端发来的消息时,触发onmessage事件,参数e.data包含server传递过来的数据
- console.log(e.data);
- let data_json = JSON.parse(e.data);
- document.getElementById("server-info").innerHTML = '收到来自“'+data_json.name+'”的消息:<br />'+data_json.message;
- str=str+data_json.message+'\n';
- // 给文本框赋值
- document.getElementById("textarea_id").value = str;
- // 跳转最后一行
- document.getElementById("textarea_id").scrollTop=document.getElementById("textarea_id").scrollHeight;
- }
- ws.onclose = function (e) {
- //当客户端收到服务端发送的关闭连接请求时,触发onclose事件
- console.log("close");
- }
- ws.onerror = function (e) {
- //如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
- console.log(error);
- }
- </script>
- </body>
- </html>
|