websocket
遇到的错误
没有弄清出端口号,旁边渊哥说,看看报错信息啊。看看后端的,没打印啊,看看前端的啊。原来是端口的问题。
实现私聊
# 客户端
# 服务端
# Http Flask 浏览器
# Websocket GeventWebsocket+Flask 客户端JavaScript(Websocket客户端)
import json
from flask import Flask,request,render_template
from geventwebsocket.handler import WebSocketHandler # 提供WS协议处理
from geventwebsocket.server import WSGIServer # 承载服务
from geventwebsocket.websocket import WebSocket # 语法提示
app = Flask(__name__)
# user_socket_dict = {nicheng:lianjie}
user_socket_dict = {}
@app.route("/my_socket/<username>")
def my_socket(username):
# 获取当前客户端与服务器的Socket连接
user_socket = request.environ.get("wsgi.websocket") # type:WebSocket
if user_socket:
user_socket_dict[username] = user_socket # bbbb = {gevent
print(len(user_socket_dict),'dict',user_socket_dict)
# print(user_socket,"OK 连接已经建立好了,接下来发消息吧")
while 1:
msg = user_socket.receive()
msg_dict = json.loads(msg)
# msg = user_socket.receive()
to_user_nick = msg_dict.get("to_user") #'bbbb'
print('toueser-nick',to_user_nick)
to_user_socket = user_socket_dict.get(to_user_nick) #'bbbb'
to_user_socket.send(msg)
@app.route("/sl")
def sl():
return render_template("sl.html")
if __name__ == '__main__':
# app.run("0.0.0.0",9527)
http_serv = WSGIServer(("0.0.0.0",9537),app,handler_class=WebSocketHandler)
http_serv.serve_forever()
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>群聊</title>
</head>
<body>
<p>我的昵称:<input type="text" id="username">
<button onclick="loginGc()">登录</button>
</p>
<p>给<input type="text" id="to_user">发送<input type="text" id="content">
<button onclick="send_msg()">发送</button>
</p>
<div id="chat_list">
</div>
</body>
<script type="application/javascript">
var ws = null;
function loginGc() {
var username = document.getElementById("username").value;
ws = new WebSocket("ws://192.168.33.57:9537/my_socket/" + username);
// 监听电话
ws.onmessage = function (eventMessage) {
console.log(eventMessage.data);
str_obj = JSON.parse(eventMessage.data);
var p = document.createElement("p");
p.innerText = str_obj.from_user +" : "+str_obj.chat;
document.getElementById("chat_list").appendChild(p);
};
};
function send_msg() {
var username = document.getElementById("username").value;
var to_user = document.getElementById("to_user").value;
var content = document.getElementById("content").value;
var sendStr = {
from_user:username,
to_user:to_user,
chat:content
};
ws.send(JSON.stringify(sendStr));
};
</script>
</html>
实现群聊
# import json
# from flask import Flask,request,render_template
# from geventwebsocket.handler import WebSocketHandler #提供 WS协议 处理
# from geventwebsocket.server import WSGIServer # 承载服务 UWsgi Werkzeug
# from geventwebsocket.websocket import WebSocket #语法提示
# app = Flask(__name__)
# user_socket_dict = {}
# @app.route('/my_socket/<username>')
# def my_socket(username):
# user_socket = request.environ.get('wsgi.websocket') #type:WebSocket #让pythcharm 提示语法提示 编译器层次
# print(user_socket,'OK 连接已经建立好了,接下来发消息把')
# if user_socket:
# user_socket_dict[username] = user_socket
# print(len(user_socket_dict),user_socket_dict)
# while 1 :
# msg = user_socket.receive()
# print(msg)
# for usocket in user_socket_dict.values():
# try :
# usocket.send(msg)
# except:
# continue
#
# @app.route('/gc')
# def gc():
# return render_template('gc.html')
#
# if __name__ == '__main__':
# http_serv = WSGIServer(('0.0.0.0',9537),app,handler_class=WebSocketHandler) #WSH 如何处理ws请求的 #WSH 建立连接
# http_serv.serve_forever() #socket_server
#
#
#
# 客户端
# 服务端
# Http Flask 浏览器
# Websocket GeventWebsocket+Flask 客户端JavaScript(Websocket客户端)
import json
from flask import Flask,request,render_template
from geventwebsocket.handler import WebSocketHandler # 提供WS协议处理
from geventwebsocket.server import WSGIServer # 承载服务
from geventwebsocket.websocket import WebSocket # 用于语法提示的
app = Flask(__name__)
user_socket_dict = {}
@app.route("/my_socket/<username>")
def my_socket(username):
# 获取当前客户端与服务器的Socket连接
user_socket = request.environ.get("wsgi.websocket") # type:WebSocket
if user_socket:
user_socket_dict[username] = user_socket
print(len(user_socket_dict), user_socket_dict)
# print(user_socket,"OK 连接已经建立好了,接下来发消息吧")
while 1:
# msg = json.loads(user_socket.receive())
msg = user_socket.receive()
print(msg)
for usocket in user_socket_dict.values():
print(usocket)
try:
usocket.send(msg)
except:
continue
@app.route("/gcs")
def gc():
return render_template("gcs.html")
if __name__ == '__main__':
# app.run("0.0.0.0",9527)
http_serv = WSGIServer(("0.0.0.0",9533),app,handler_class=WebSocketHandler)
http_serv.serve_forever()
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p>我的昵称:<input type="text" id="username"><button onclick="loginGc()">登陆</button></p>
<p><input type="text" id="content"> <button onclick="send_msg()">发送</button></p>
<div id="chat_list">
</div>
</body>
<script type="application/javascript">
var ws = null;
function loginGc() {
var username = document.getElementById('username').value;
ws = new WebSocket('ws://192.168.33.57:9533/my_socket/'+username);
ws.onmessage = function (eventMessage) {
console.log(eventMessage.data);
str_obj = JSON.parse(eventMessage.data);
var p = document.createElement('p');
p.innerText = str_obj.from_user +" : "+str_obj.chat;
document.getElementById('chat_list').appendChild(p);
};
}
function send_msg() {
var content = document.getElementById('content').value;
var username = document.getElementById('username').value;
var sendStr = {
from_user : username,
chat : content
};
ws.send(JSON.stringify(sendStr));
};
</script>
</html>