websocket实现简单的单聊

Posted zhao-peng-

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了websocket实现简单的单聊相关的知识,希望对你有一定的参考价值。

技术图片
 1 import json
 2 
 3 from flask import Flask, request, render_template
 4 
 5 from geventwebsocket.handler import WebSocketHandler
 6 from gevent.pywsgi import WSGIServer
 7 from geventwebsocket.websocket import WebSocket
 8 
 9 app = Flask(__name__)
10 
11 user_socket_dict = {}
12 
13 
14 @app.route(/conn_ws<suer>)
15 def ws_app(suer):
16     # print(request.environ)
17 
18     user_socket = request.environ.get(wsgi.websocket)  # type: WebSocket
19     user_socket_dict[suer] = user_socket
20     print(len(user_socket_dict), list(user_socket_dict))
21     while True:
22         msg = user_socket.receive()
23         msg_dict = json.loads(msg)
24         to_user = msg_dict.get(to_user)
25         to_user_socket = user_socket_dict.get(to_user)
26         to_user_socket.send(msg)
27 
28 
29 @app.route(/index)
30 def index():
31     return render_template(my_dws.html)
32 
33 
34 if __name__ == __main__:
35     http_serv = WSGIServer((0.0.0.0, 9527), app, handler_class=WebSocketHandler)
36 
37     http_serv.serve_forever()
后端
技术图片
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <p>
 9     <input type="text" id="nick">
10     <button onclick="login()">登录聊天</button>
11 </p>
12 
13 发送给:<input type="text" id="to_user">
14 消息:<input type="text" id="send_str">
15 <button id="send_btn" onclick="send()">发送消息</button>
16 
17 <p>
18 
19 <div id="chat_list"></div>
20 
21 </p>
22 </body>
23 <script type="application/javascript">
24     var ws = null;
25 
26     function login() {
27         var nick = document.getElementById(nick).value;
28         ws = new WebSocket(ws://192.168.11.67:9527/conn_ws + nick);
29         ws.onmessage = function (messageEvent) {
30             console.log(messageEvent.data);
31             var ptag = document.createElement(p);
32             var message = JSON.parse(messageEvent.data);
33 
34             ptag.innerText = message.from_user + : + message.message;
35             document.getElementById(chat_list).appendChild(ptag);
36         };
37     }
38 
39     function send() {
40         var message = document.getElementById(send_str).value;
41         var send_str = {
42             from_user: document.getElementById(nick).value,
43             to_user: document.getElementById(to_user).value,
44             message: message
45         };
46         var json_send_str = JSON.stringify(send_str);
47         ws.send(json_send_str);
48     }
49 </script>
50 </html>
前端

 

以上是关于websocket实现简单的单聊的主要内容,如果未能解决你的问题,请参考以下文章

spring websocket 和socketjs实现单聊群聊,广播的消息推送详解

websocket实现单聊

SpringBoot实现WebSocket单聊

websocket实现群聊和单聊(转)

websocket 群聊,单聊,加密,解密

175. Spring Boot WebSocket:单聊