WebSocket群聊与单聊
一 . WebSocket实现群聊
py文件代码
# py文件
from flask import Flask, render_template, request
from geventwebsocket.handler import WebSocketHandler
from geventwebsocket.websocket import WebSocket
from geventwebsocket.exceptions import WebSocketError
from gevent.pywsgi import WSGIServer app = Flask(__name__) user_socket_list = [] @app.route('/index')
def index():
return render_template('index.html') @app.route('/my/ws')
def my_ws():
# 当前端声明WebSocket的时候才有wsgi.websocket
user_socket = request.environ.get('wsgi.websocket') # type:WebSocket # 为了让下面user_socket点的时候有提示
user_socket_list.append(user_socket)
print(len(user_socket_list), user_socket_list) while 1:
try: # 下面用图解释为什么要try
msg = user_socket.receive() # 阻塞等待发送信息
except WebSocketError:
user_socket_list.remove(user_socket)
return 'GoodBye'
for user in user_socket_list:
if user == user_socket:
continue
try:
user.send(msg)
except:
continue if __name__ == '__main__':
# 用下面这种方法启动是为了识别并支持websocket
http_server = WSGIServer(('0.0.0.0', 9527), app, handler_class=WebSocketHandler)
http_server.serve_forever()
html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<p><input type="text" id="message">
<button onclick="send_message()">发送</button>
</p>
<div id="chat_list"> </div>
</body>
<script type="application/javascript">
var ws = new WebSocket('ws://127.0.0.1:9527/my/ws');
ws.onmessage = function (MessageEvent) { //当接收到消息的时候执行MessageEvent函数
var p = document.createElement('p'); // 创建一个p标签
p.innerText = MessageEvent.data; // 给p标签里面添加数据
document.getElementById('chat_list').appendChild(p); // 把p标签添加到div标签里面
}; function send_message() {
var message = document.getElementById('message').value;
ws.send(message)
}
</script>
</html>
不try的时候
try之后
二 . 单聊
py文件
import json
from flask import Flask, render_template, request
from geventwebsocket.handler import WebSocketHandler
from geventwebsocket.websocket import WebSocket
from geventwebsocket.exceptions import WebSocketError
from gevent.pywsgi import WSGIServer app = Flask(__name__)
user_socket_dict = {} @app.route('/home')
def index():
return render_template('home.html') @app.route('/my/ws/<username>')
def my_ws(username):
user_socket = request.environ.get('wsgi.websocket') # type:WebSocket
user_socket_dict[username] = user_socket
print(len(user_socket_dict), user_socket_dict)
while 1:
try:
msg = user_socket.receive() # 阻塞等待消息
# print(msg, type(msg))
msg_dict = json.loads(msg)
to_user = msg_dict.get('to_user')
to_user_socket = user_socket_dict.get(to_user)
to_user_socket.send(msg)
except WebSocketError:
user_socket_dict.pop(username)
return 'GoodBye' if __name__ == '__main__':
http_server = WSGIServer(('0.0.0.0', 9527), app, handler_class=WebSocketHandler)
http_server.serve_forever()
html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body> <p>发送者<input type="text" id="username">
<button onclick="open_chat()">开始聊天</button> <!--onclick就是点击执行里面函数-->
</p>
<p>接受者 <input type="text" id="to_user"></p>
<p>
消息 <input type="text" id="message">
<button onclick="SendMessage()">发送</button>
</p>
<div id="chat_list"> </div>
</body>
<script type="application/javascript">
var ws = null; //声明一个全局变量
function open_chat() {
var username = document.getElementById('username').value;
ws = new WebSocket('ws://127.0.0.1:9527/my/ws/' + username);
ws.onopen = function () { // onopen函数就是当你连接开始时执行
alert('欢迎' + username + '来到午夜激情聊天室!')
};
ws.onmessage = function (MessageEvent) {
var chat = JSON.parse(MessageEvent.data);
var p = document.createElement('p');
p.style.cssText = 'width:270px;text-align: left';
p.innerText = chat.from_user + '->' + chat.message;
document.getElementById('chat_list').appendChild(p);
};
ws.onclose = function () { // onclose函数就是如果断开连接了执行函数
// 断开连接
console.log('已经断开连接');
};
} function SendMessage() {
var message = document.getElementById('message').value;
var from_user = document.getElementById('username').value;
var to_user = document.getElementById('to_user').value;
var send_str = {
from_user: from_user,
to_user: to_user,
message: message
};
ws.send(JSON.stringify(send_str));
var p = document.createElement('p');
p.style.cssText = 'width:270px;text-align:right';
p.innerText = send_str.message + '<-大帅比';
document.getElementById('chat_list').appendChild(p);
}
</script>
</html>
展示结果:
WebSocket群聊与单聊的更多相关文章
- spring websocket 和socketjs实现单聊群聊,广播的消息推送详解
spring websocket 和socketjs实现单聊群聊,广播的消息推送详解 WebSocket简单介绍 随着互联网的发展,传统的HTTP协议已经很难满足Web应用日益复杂的需求了.近年来,随 ...
- 一套高可用、易伸缩、高并发的IM群聊、单聊架构方案设计实践
一套高可用.易伸缩.高并发的IM群聊.单聊架构方案设计实践 一套高可用.易伸缩.高并发的IM群聊.单聊架构方案设计实践-IM开发/专项技术区 - 即时通讯开发者社区! http://www.52im. ...
- Websocket实现群聊、单聊
Websocket 使用的第三方模块:gevent-websocket 群聊 ws群聊.py中的内容 from flask import Flask, request, render_template ...
- websocket实现群聊和单聊(转)
昨日内容回顾 1.Flask路由 1.endpoint="user" # 反向url地址 2.url_address = url_for("user") 3.m ...
- flask + websocket实现简单的单聊和群聊
单聊 from flask import Flask,request,render_template from geventwebsocket.handler import WebSocketHand ...
- Flask实现简单的群聊和单聊
Flask是使用python写的一个简单轻量级的框架,今天我们使用Flask实现一个简单的单聊和群聊功能 . 主要思路 : 前端登录聊天室,聊天室信息包含用户的登录信息,相当于一个登录功能,会把这个信 ...
- Flask+WebSocket实现群聊与单聊功能
在开始我们的程序代码之前,先来了解一下相关的基础知识: 1.什么是websocket? (1)WebSocket是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议.WebSocket ...
- 如何用WebSocket实现一个简单的聊天室以及单聊功能
百度百科中这样定义WebSocket:WebSocket协议是基于TCP的一种新的网络协议.它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端.简单的说,We ...
- websocket 实现单聊群聊 以及 握手原理+加密方式
WebSocket 开始代码 服务端 群聊 # type:WebSocket 给变量标注类型 # websocket web + socket from geventwebsocket.server ...
随机推荐
- 论文学习-系统评估卷积神经网络各项超参数设计的影响-Systematic evaluation of CNN advances on the ImageNet
博客:blog.shinelee.me | 博客园 | CSDN 写在前面 论文状态:Published in CVIU Volume 161 Issue C, August 2017 论文地址:ht ...
- 玩转SpringBoot之定时任务详解
序言 使用SpringBoot创建定时任务非常简单,目前主要有以下三种创建方式: 一.基于注解(@Scheduled) 二.基于接口(SchedulingConfigurer) 前者相信大家都很熟悉, ...
- oracle数据库导出表结构步骤
导出完成后在状态栏中显示Find
- C# 连接/查询Jira
查询jira数据,如果是前端,可以按照如下格式直接访问,获取数据 http://jira.company.com/rest/api/2/search?jql=project = REM AND res ...
- sql 查询 某字段 重复次数 最多的记录
需求 查询小时气象表中 同一日期.同一城市.同意检测站点 首要污染物出现出书最多的记录 第一步: 添加 排序字段 select StationID,RecordDate,CityID,Primar ...
- servlet doGet()方法获取字符串乱码问题
当你遇到ajax向servlet发送数据出现乱码问题的时候不要惊慌,现有以下两个解决办法 (1)在doGet和doPost方法中添加以下代码 request.setCharactersEncoding ...
- Git创建本地版本库
什么是版本库呢?版本库又名仓库,英文名repository,你可以简单理解成一个目录,这个目录里面的所有文件都可以被Git管理起来,每个文件的修改.删除,Git都能跟踪,以便任何时刻都可以追踪历史,或 ...
- Ubuntu 服务器443端口证书配置
配置虚拟主机: cd /etc/apache2/sites-available 从默认的模板文件中复制过来一份进行自己的配置: sudo cp ./default-ssl.conf ./mysite1 ...
- 【Linux】【MySQL】CentOS7安装最新版MySQL8.0.13(最新版MySQL从安装到运行)
1.前言 框框博客在线报时:2018-11-07 19:31:06 当前MySQL最新版本:8.0.13 (听说比5.7快2倍) 官方之前表示:MySQL 8.0 正式版 8.0.11 已发布,MyS ...
- HTML导出excel
在博客园找到的相关问题http://q.cnblogs.com/q/12952 还有相关的回答http://www.cnblogs.com/zhouxin/archive/2009/12/11/16 ...