websocket实现单聊

Posted 小学弟-

tags:

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

server
#
@File: ws from flask import Flask, request, render_template from geventwebsocket.handler import WebSocketHandler from geventwebsocket.websocket import WebSocket # 我用来做语法提示 from gevent.pywsgi import WSGIServer import json app = Flask(__name__) # type:Flask # 存放用户对应的,收件人,发件人,以及信息 # 可以做聊天室 {聊天室id:[], 聊天室id:[]...} # 两个用户之间的聊天{"用户名":{信息}, "用户名":{信息}} user_socket_dict = {} # type:dict @app.route(/) def index(): return render_template(single.html) @app.route("/ws/<user>") def ws(user): user_socket = request.environ.get(wsgi.websocket) # type:WebSocket if user_socket: user_socket_dict[user] = user_socket print(len(user_socket_dict), user_socket_dict) while 1: msg = user_socket.receive() print(msg) # b"{from_user:xx, to_user:xx,msg:xx}" msg_dict = json.loads(msg) to_usocket = user_socket_dict.get(msg_dict.get("to_user")) # type:WebSocket to_usocket.send(json.dumps({"from_user": user, "to_user": msg_dict.get("to_user"), "msg": msg_dict.get("msg")})) if __name__ == __main__: http_server = WSGIServer(("0.0.0.0", 5000), app, handler_class=WebSocketHandler) http_server.serve_forever()

 

single.html


<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> </head> <body> <p>您的昵称:<input type="text" id="nick"> <button onclick="openws()">进入聊天室</button> </p> <p>给<input type="text" id="to_user">发送:<input type="text" id="message"> <button onclick="send_msg()">发送消息</button> </p> <div id="msg_list" style="width: 500px;"> </div> </body> <script type="application/javascript"> var ws = null; // ws.onopen = function(){ // alert("欢迎来到S14群喷"); // }; function openws() { var nick = document.getElementById("nick").value; ws = new WebSocket("ws://192.168.12.41:5000/ws/" + nick); ws.onmessage = function (ws_status) { console.log(ws_status.data); var msg_obj = JSON.parse(ws_status.data); var ptag = document.createElement("p"); ptag.innerText = msg_obj.from_user + " : " + msg_obj.msg; document.getElementById("msg_list").appendChild(ptag); }; } function send_msg() { var msg = document.getElementById("message").value; var from_user = document.getElementById("nick").value; var to_user = document.getElementById("to_user").value; var ptag = document.createElement("p"); ptag.style.cssText = "text-align: right;"; ptag.innerText = msg + " : " + from_user; document.getElementById("msg_list").appendChild(ptag); var msg_obj = { msg: msg, from_user: from_user, to_user: to_user }; ws.send(JSON.stringify(msg_obj)); }; </script> </html>

 

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

SpringBoot实现WebSocket单聊

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

websocket实现群聊和单聊(转)

基于websocket的单聊.群聊

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

175. Spring Boot WebSocket:单聊