websocket消息服务

 

目的:搭建websocket服务,用浏览器与服务进行消息交互(写的第一个Go程序)

 

代码目录结构:

Go语言 websocket

 

前端html页面:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <script>
 6         window.addEventListener("load", function(evt) {
 7             var output = document.getElementById("output");
 8             var input = document.getElementById("input");
 9             var ws;
10             var print = function(message) {
11                 var d = document.createElement("div");
12                 d.innerHTML = message;
13                 output.appendChild(d);
14             };
15             document.getElementById("open").onclick = function(evt) {
16                 if (ws) {
17                     return false;
18                 }
19                 ws = new WebSocket("ws://127.0.0.1:7777/ws");
20                 ws.onopen = function(evt) {
21                     print("OPEN");
22                 }
23                 ws.onclose = function(evt) {
24                     print("CLOSE");
25                     ws = null;
26                 }
27                 ws.onmessage = function(evt) {
28                     print("RESPONSE: " + evt.data);
29                 }
30                 ws.onerror = function(evt) {
31                     print("ERROR: " + evt.data);
32                 }
33                 return false;
34             };
35             document.getElementById("send").onclick = function(evt) {
36                 if (!ws) {
37                     return false;
38                 }
39                 print("SEND: " + input.value);
40                 ws.send(input.value);
41                 return false;
42             };
43             document.getElementById("close").onclick = function(evt) {
44                 if (!ws) {
45                     return false;
46                 }
47                 ws.close();
48                 return false;
49             };
50         });
51     </script>
52 </head>
53 <body>
54 <table>
55     <tr><td valign="top" width="50%">
56         <p>Click "Open" to create a connection to the server,
57             "Send" to send a message to the server and "Close" to close the connection.
58             You can change the message and send multiple times.
59         </p>
60             <form>
61                 <button id="open">Open</button>
62                 <button id="close">Close</button>
63             <input id="input" type="text" value="Hello world!">
64             <button id="send">Send</button>
65             </form>
66     </td><td valign="top" width="50%">
67         <div id="output"></div>
68     </td></tr></table>
69 </body>
70 </html>
client.html

相关文章:

  • 2021-06-19
  • 2021-11-21
  • 2021-07-31
  • 2021-11-29
  • 2021-05-19
  • 2022-12-23
  • 2021-11-01
  • 2021-12-18
猜你喜欢
  • 2022-12-23
  • 1970-01-01
  • 2022-12-28
  • 2021-10-18
  • 2020-11-06
  • 2020-03-26
  • 2021-10-16
相关资源
相似解决方案