server

from flask import Flask, request, render_template
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from geventwebsocket.websocket import WebSocket
import json
app = Flask(__name__) user_socket_dict = {} # 字典 @app.route('/conn_ws/<user_nick>') #http 协议,
def ws_app(user_nick): user_socket = request.environ.get('wsgi.websocket') #type:WebSocket
user_socket_dict[user_nick] = user_socket # { 昵称:user信息 }
print(len(user_socket_dict), list(user_socket_dict.keys())) while True: # user_socket 是一个内存地址
msg = user_socket.receive() # hang 住了
msg_dict = json.loads(msg) to_user = msg_dict.get('to_user')
if to_user == 'all':
for ss in list(user_socket_dict.values()):
ss.send(msg) else: to_user_socket = user_socket_dict.get(to_user)
to_user_socket.send(msg) @app.route('/')
def index():
return render_template('my_ws.html') if __name__ == '__main__':
# app.run()
http_ser = WSGIServer(('0.0.0.0',9009),app,handler_class=WebSocketHandler) # 应用程序网关接口
http_ser.serve_forever()

页面 html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>单聊</title>
</head>
<body>
<p><input type="text" id="nick">
<button onclick="login()">登陆聊天室</button>
</p> 发送给: <input type="text" id="to_user" placeholder="找谁聊?"> 消息: <input type="text" id="send_str"> <button id="sin_btn" onclick="sin_send()">发消息</button>
<button id="send_btn" onclick="send()">群聊发消息</button> <p>
<div id="chat_list">
</div>
</p> </body>
<script type="text/javascript">
var ws = null; //公共变量, function login() {
var nick = document.getElementById('nick').value;
ws = new WebSocket('ws://192.168.11.94:9009/conn_ws/' + nick); //登录时候创建连接
ws.onmessage = function (messageEvent) { //等待消息
console.log(messageEvent.data);
var ptag = document.createElement('p');
var message = JSON.parse(messageEvent.data); ptag.innerText = message.from_user + ' : ' + message.message;
document.getElementById('chat_list').appendChild(ptag);
};
} function send() {
var message = document.getElementById('send_str').value;
var send_str = {
from_user: document.getElementById('nick').value,
// to_user:document.getElementById('to_user').value,
to_user: 'all', // 群聊
message: message
};
var json_str = JSON.stringify(send_str);
ws.send(json_str);
} function sin_send() {
var message = document.getElementById('send_str').value;
var send_str = {
from_user: document.getElementById('nick').value,
to_user:document.getElementById('to_user').value, message: message
};
var json_str = JSON.stringify(send_str);
ws.send(json_str);
} // js代码是异步代码;
</script>
</html>

websocket 二合一的更多相关文章

  1. 【老司机经验】CC2530&STM8S105二合一嵌入式学习板设计思路与经验分享

    CC2530&STM8S105二合一嵌入式学习板设计思路与经验分享 1.缘起    这些年来一直在其他公司的实验箱和别人的开发板上进行教学与开发工作,总是觉得功能设计不那么合意.心里突然冒出个 ...

  2. mobile_轮播图_transform 版本_transform 读写二合一

    轮播图_transform 版本 关键点: 2D 变换 transform 不会改变 元素 在 文档流 中的位置 定位 position 会改变 元素 在 文档流 中的位置 语句解析太快,使用 set ...

  3. 插入数据返回自增id及插入更新二合一

    原文https://blog.csdn.net/dumzp13/article/details/50984413 JDBC: con.setAutoCommit(false); String sql ...

  4. 【洛谷2468】[SDOI2010] 粟粟的书架(二合一)

    点此看题面 大致题意: 问你选取一个矩形区间内至少几个数,才能使它们的和\(\ge H_i\). 二合一 根据数据范围,比较显然能看出它是一道二合一的题目. 对于第一种情况,\(R,C\le 200\ ...

  5. 一步一步学WebSocket(二) 使用SuperWebSocket实现自己的服务端

    上一篇文章,我们了解了客户端如何与服务器创建WebSocket连接.但是一个巴掌拍不响,既然是通信,就必然最少要有两个端.今天我们来看看c#如何用已有的框架实现一个WebSocket服务端. 在.Ne ...

  6. 学习WebSocket(二):使用Spring WebSocket做一个简单聊天室

    聊天室高频率.低延时完全符合websocket的特点,所以聊天室使用websocket再适合不过了. 聊天室的功能并没有比上一节代码多多少,主要在握手阶段对用户的session做处理,对用户的消息进行 ...

  7. websocket(二)--简单实现网页版群聊

    websocket可以实现服务端的消息推送,而不必在客户端轮询,大大的节省的资源,对于实时通讯来说简直是个大喜讯. 在上一篇文章中介绍了协议握手,这篇文章将通过实现简单的群聊来帮助进一步了解webso ...

  8. websocket(二)——基于node js 的同步聊天应用

      https://github.com/sitegui/nodejs-websocket 1.用node搭建本地服务 npm install nodejs-websocket var ws = re ...

  9. 注册登录二合一之bootstrap

    来源 https://bootsnipp.com/snippets/featured/login-and-register-tabbed-form jquery插件 需导入bootstrap插件 这个 ...

随机推荐

  1. Adding ASP.NET MVC5 Identity Authentication to an existing project

    Configuring Identity to your existing project is not hard thing. You must install some NuGet package ...

  2. 208道最常见的Java面试题整理(面试必备)

    适宜阅读人群 需要面试的初/中/高级 java 程序员 想要查漏补缺的人 想要不断完善和扩充自己 java 技术栈的人 java 面试官 具体面试题 下面一起来看 208 道面试题,具体的内容. 一. ...

  3. 内建模块collections的使用

    # -*-coding:utf-8 -*- from collections import namedtuple Point=namedtuple('Point',['x','y']) p=Point ...

  4. Win2008R2+Apache+PHP+Tomcat配置

    一.VC运行库 对于Apache和PHP,在Windows上运行的话都需要对应VC运行库的支持,即Apache.PHP和VC运行库这三者的版本必须相对应,这就会带来很多问题,比如下了较新的Apache ...

  5. 【CF480D】Parcels DP

    [CF480D]Parcels 题意:有一个栈,有n个物品,每个物品可以选或不选.如果选了第i个物品,则获得$v_i$的收益,且第i个物品必须在$in_i$时刻入栈,$out_i$时刻出栈.每个物品还 ...

  6. 实现Ajax异步的layui分页

    https://www.e-learn.cn/content/java/1084522

  7. poj2251_kuagnbin带你飞专题一

    Dungeon Master Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 32684   Accepted: 12529 ...

  8. Educational Codeforces Round 1

    598A - Tricky Sum    20171103$$ans=\frac{n(n+1)}{2} - 2\sum_{k=0}^{\left \lfloor \log_2 n \right \rf ...

  9. vue利用vue ui命令创建项目

    上次用git bash,用create 命令创建vue项目,这是玩个炫酷的------vue ui (前提是有安装node.js). 在目标文件  vue ui 可以看到他在8000端口出现了一个gu ...

  10. Gym 102056I - Misunderstood … Missing - [DP][The 2018 ICPC Asia-East Continent Final Problem I]

    题目链接:https://codeforces.com/gym/102056/problem/I Warm sunshine, cool wind and a fine day, while the ...