使用websocket实现单聊和多聊
单聊:
前端:
<!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("欢迎来到群喷");
// }; function openws(){
var nick = document.getElementById("nick").value;
ws = new WebSocket("ws://192.168.12.10: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>
后端:
from flask import Flask,request,render_template
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
import json from geventwebsocket.websocket import WebSocket app = Flask(__name__)
user_socket_dict = { } @app.route('/ws/<user>')
def ws(user):
user_socket = request.environ.get('wsgi.websocket') #原请求
if user_socket:
user_socket_dict[user] = user_socket while 1:
msg = user_socket.receive()
msg_dict = json.loads(msg)
to_usocket = user_socket_dict.get(msg_dict.get("to_user"))
to_usocket.send(json.dumps({"from_user": user, "to_user": msg_dict.get("to_user"), "msg": msg_dict.get("msg")})) @app.route("/")
def index():
return render_template("ws_one.html") if __name__ == '__main__':
# app.run("0.0.0.0",5000,debug=True)
http_serv = WSGIServer(("0.0.0.0", 5000), app, handler_class=WebSocketHandler)
http_serv.serve_forever()
多聊:
前端
<!DOCTYPE html>
<html lang="zn-CN">
<head>
<meta 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="message"> <button onclick="send_msg()">发送消息</button></p>
<div id="msg_list" style="width: 500px"></div>
</body> <script type="application/javascript">
var ws = new WebSocket("ws://192.168.12.10:5000/ws");
// ws.onopen = function(){ //当打开的时候发送消息
// ws.send('hello')
// };
ws.onmessage = function (ws_status) {
console.log(ws_status.data);
var ptag = document.createElement('p');
ptag.innerText = ws_status.data;
document.getElementById('msg_list').appendChild(ptag)
};
function send_msg() {
var msg = document.getElementById('message').value;
var ptag = document.createElement('p');
ptag.style.cssText = 'text-align:right;';
ptag.innerText = msg;
document.getElementById('msg_list').appendChild(ptag)
ws.send(msg)
} </script>
</html>
后端:
from flask import Flask,request,render_template
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from geventwebsocket.websocket import WebSocket app = Flask(__name__) user_socker_list = []
@app.route('/ws')
def ws():
user_socker = request.environ.get('wsgi.websocket') #type:WebSocket
if user_socker:
user_socker_list.append(user_socker)
print(len(user_socker_list), user_socker_list)
while 1:
msg = user_socker.receive()
print(msg)
for usocker in user_socker_list:
if user_socker == usocker:
continue
try:
usocker.send(msg)
except:
continue
@app.route('/')
def index():
return render_template('ws_all.html') if __name__ == '__main__':
# app.run(debug=True)
http_serv = WSGIServer(("0.0.0.0",5000),app,handler_class=WebSocketHandler)
http_serv.serve_forever()
使用websocket实现单聊和多聊的更多相关文章
- websocket 实现单聊群聊 以及 握手原理+加密方式
WebSocket 开始代码 服务端 群聊 # type:WebSocket 给变量标注类型 # websocket web + socket from geventwebsocket.server ...
- SignalR快速入门 ~ 仿QQ即时聊天,消息推送,单聊,群聊,多群公聊(基础=》提升)
SignalR快速入门 ~ 仿QQ即时聊天,消息推送,单聊,群聊,多群公聊(基础=>提升,5个Demo贯彻全篇,感兴趣的玩才是真的学) 官方demo:http://www.asp.net/si ...
- flask 第五章 WebSocket GeventWebsocket 单聊群聊 握手 解密 加密
1.WebSocket 首先我们来回顾一下,我们之前用socket学习过的项目有: 1.django 2.flask 3.FTP - 文件服务 HTTP - TCP (特点): 1.一次请求,一次响应 ...
- 基于websocket的单聊.群聊
关于ai.baidu.com的 代码: #########################################核心代码################################### ...
- flask + websocket实现简单的单聊和群聊
单聊 from flask import Flask,request,render_template from geventwebsocket.handler import WebSocketHand ...
- websocket实现单聊
server# @File: ws from flask import Flask, request, render_template from geventwebsocket.handler imp ...
- ASP.NET SignalR 与 LayIM2.0 配合轻松实现Web聊天室(三) 之 实现单聊,群聊,发送图片,文件。
上篇讲解了如何搭建聊天服务器,以及客户端js怎么和layui的语法配合.服务器已经连接上了,那么聊天还会远吗? 进入正题,正如上一篇提到的我们用 Client.Group(groupId)的方法向客户 ...
- happyChat开发系列:使用websocket.io实现双向通信的乐聊大前端开发
一.前言 乐聊是一个自己用websocket写一个完整的应用,虽然功能比较欠缺,但是实现了基本的文字聊天,以及群聊,私聊,机器人聊天等功能.因为这个自己做了PC端,无线端(手机端),以及使用cordo ...
- netty无缝切换rabbitmq、activemq、rocketmq实现聊天室单聊、群聊功能
netty的pipeline处理链上的handler:需要IdleStateHandler心跳检测channel是否有效,以及处理登录认证的UserAuthHandler和消息处理MessageHan ...
随机推荐
- R 《回归分析与线性统计模型》page140,5.1
rm(list = ls()) library(car) library(MASS) library(openxlsx) A = read.xlsx("data140.xlsx") ...
- 关于AlertDialog多选框中全选和反选的实现办法
package mobile.android.ch07.multi.choice.dialog; import android.app.Activity; import android.app.Ale ...
- 016、Java中使用小数
01.代码如下: package TIANPAN; /** * 此处为文档注释 * * @author 田攀 微信382477247 */ public class TestDemo { public ...
- 001.Delphi插件之QPlugins,一个最简单的插件
安装QPlugins里面的Demo,复制粘贴着写了一个最简单的插件,看看好不好用 EXE代码如下: unit Main_Frm; interface uses Winapi.Windows, Wina ...
- http https 干货
HTTPS原理 在谈HTTPS原理之前,首先了解一下Http和Https的区别. Http(全称:Hyper Text Transfer Protocol),一般称为超文本传输协议,也是互联 ...
- 吴裕雄 Bootstrap 前端框架开发——Bootstrap 字体图标(Glyphicons):glyphicon glyphicon-inbox
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name ...
- 吴裕雄 Bootstrap 前端框架开发——Bootstrap 字体图标(Glyphicons):glyphicon glyphicon-cog
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name ...
- mybaits-plus总结
import java.math.BigDecimal; import java.util.Arrays; import java.util.Date; import java.util.List; ...
- 不能安装64位office提示已安装32位如何处理
不能安装64位office提示已安装32位如何处理? 1 2 3 4 5 6 当你遇到提示说[无法安装64位版本的office,以为在您的PC上找一下32位程序......]时如果你还想安装64位 ...
- require(): open_basedir restriction in effect. File(/www/wwwroot/xcx/zerg/thinkphp/start.php) is not within the allowed path(s): (/www/wwwroot/xcx/zerg/public/:/tmp/:/proc/) in /www/wwwroot/xcx/zerg/p
解决方法: 在如下文件增加一项(如图所示) 在如下文件增加一项(如图所示): #php文件采用fastcgi解析并设置参数 location ~ \.php { try_files ...