python與html5 websocket開發聊天對話窗

1.下載必須的包 https://github.com/Pithikos/python-websocket-server,解壓縮並把文檔夾名‘python-websocket-server-master’ 改為‘websocket’

python與html5 websocket開發聊天對話窗
python與html5 websocket開發聊天對話窗

2.websocket文檔夾內只保留websocket_server文檔夾和server.py

python與html5 websocket開發聊天對話窗
python與html5 websocket開發聊天對話窗

3.稍微修改server.py的源碼

 1 from websocket_server import WebsocketServer
 2 
 3 # Called for every client connecting (after handshake)
 4 def new_client(client, server):
 5         print("New client connected and was given id %d" % client['id'])
 6         #server.send_message_to_all("a new client...")
 7         server.send_message(client,"請問有什麼可以幫到您?")
 8 
 9 
10 # Called for every client disconnecting
11 def client_left(client, server):
12         print("Client(%d) disconnected" % client['id'])
13 
14 
15 # Called when a client sends a message
16 def message_received(client, server, message):
17         if len(message) > 200:
18                 message = message[:200]+'..'
19         print("Client(%d)_address%s said: %s" % (client['id'],client['address'], message))
20         server.send_message(client,'用户編號'+str(client['id'])+':'+message)
21 
22 
23 PORT=9001
24 server = WebsocketServer(PORT,host="192.168.150.128")
25 server.set_fn_new_client(new_client)
26 server.set_fn_client_left(client_left)
27 server.set_fn_message_received(message_received)
28 server.run_forever()

4.編輯client.html

 1 <!DOCTYPE html>
 2 <html>
 3    <head>
 4    <meta charset="utf-8">
 5    <title>html5 websocket特性</title>
 6    <style>
 7       body{
 8          overflow: hidden;
 9       }
10       h2{
11          margin-top: 30px;
12          text-align: center;
13          background-color: #393D49;
14          color: #fff;
15          font-weight: normal;
16          padding: 15px 0
17       }
18       #chat{
19          text-align: center;
20         
21       }
22       #win{
23          margin-top: 20px;
24          text-align: center;
25       }
26       #sse{
27          margin-top: 10px;
28          text-align: center;
29       }
30       #sse button{
31          background-color: #009688;
32          color: #fff;
33          height: 40px;
34          border: 0;
35          border-radius: 3px 3px;
36          padding-left: 10px;
37          padding-right: 10px;
38          cursor: pointer;
39       }
40    </style>
41    <script src="/static/js/jquery.min.js"></script>        
42    </head>
43    <body>
44       <h2>聊天室</h2>
45       <div id="chat">
46           <textarea id="history" cols="80" rows="40"></textarea>
47       </div>
48 
49       <div id="win">
50          <textarea id="messagewin" cols="80" rows="5"></textarea>
51       </div>
52       
53       <div id="sse">
54          <button onclick="sendMessage()">發送對話</button>
55       </div>
56       
57       <script type="text/javascript">      
58       var oHistory = $('#history');
59       var oWin = $('#messagewin');
60 
61       if ("WebSocket" in window){
62          console.log("您的瀏覽器支持 WebSocket!");
63          var ws = new WebSocket("ws://192.168.150.128:9001");
64         //var ws = new WebSocket("ws://localhost:9001");
65          ws.onopen = function(){
66             console.log("websocket 已連接上");
67          }
68 
69          ws.onmessage = function (evt) { 
70             var dataReceive = evt.data;
71             console.log("數據已接收..."+dataReceive);
72             $('#history').val($('#history').val()+dataReceive+"\n");
73          };
74 
75          ws.onclose = function()
76             { 
77               console.log("連接已關閉..."); 
78          };
79 
80       }else{
81          // 瀏覽器不支持 WebSocket
82          console.log("您的瀏覽器不支持 WebSocket!");
83       }
84       
85       function sendMessage(){
86          var dataSend = oWin.val().trim();
87          ws.send(dataSend);
88          oWin.val('');
89       }
90         
91    </script>
92    </body>
93 </html>
python與html5 websocket開發聊天對話窗
python與html5 websocket開發聊天對話窗

界面

3.終端運行server.py,然後通過瀏覽器訪問client.html進行連接

python與html5 websocket開發聊天對話窗
python與html5 websocket開發聊天對話窗

終端運行server.py

python與html5 websocket開發聊天對話窗
python與html5 websocket開發聊天對話窗

瀏覽器訪問對話客户端

python與html5 websocket開發聊天對話窗
python與html5 websocket開發聊天對話窗

終端顯示

4.接着嘗試在客户端發送一句話

python與html5 websocket開發聊天對話窗
python與html5 websocket開發聊天對話窗
python與html5 websocket開發聊天對話窗
python與html5 websocket開發聊天對話窗
python與html5 websocket開發聊天對話窗
python與html5 websocket開發聊天對話窗