这里先放一个python2的websocket【代码】
我一开始以为随便改一下python2和python3的兼容就可以直接运行了。谁知道,人算不如天算天算,搞了我一天都没搞好。然后弃坑,不做伸手党,万事靠自己。当然有半天我跑去看辻本杏去了,说实话什么波姐,什么三上,什么julia,都不中我胃口,就譬如桃乃木什么的偏正常体型的才是正宗。
言归正传
好了言归正传,开起车来就要炸了。
python的 websockets模块(这个找了很久)
#安装
pip install websockets
pip3 install websockets
英文文档的话真没有,别说什么中文文档了,对于我这新手来说只能github一波https://github.com/aaugustin/websockets/tree/master/example
好了,直接看例子算了
这个可以实现多人聊天,我就来改一改,这个是"conter.py"例子,html我就不放了,太简单了
#!/usr/bin/env python
# WS server example that synchronizes state across clients
import asyncio
import json
import logging
import websockets
logging.basicConfig()
STATE = {'value': 0}
USERS = set()
def state_event():
return json.dumps({'type': 'state', **STATE})
def users_event():
return json.dumps({'type': 'users', 'count': len(USERS)})
async def notify_state():
if USERS: # asyncio.wait doesn't accept an empty list
message = state_event()
await asyncio.wait([user.send(message) for user in USERS])
async def notify_users():
if USERS: # asyncio.wait doesn't accept an empty list
message = users_event()
await asyncio.wait([user.send(message) for user in USERS])
async def register(websocket):
USERS.add(websocket)
await notify_users()
async def unregister(websocket):
USERS.remove(websocket)
await notify_users()
async def counter(websocket, path):
# register(websocket) sends user_event() to websocket
await register(websocket)
try:
await websocket.send(state_event())
async for message in websocket:
data = json.loads(message)
if data['action'] == 'minus':
STATE['value'] -= 1
await notify_state()
elif data['action'] == 'plus':
STATE['value'] += 1
await notify_state()
else:
logging.error(
"unsupported event: {}", data)
finally:
await unregister(websocket)
asyncio.get_event_loop().run_until_complete(
websockets.serve(counter, 'localhost', 6789))
asyncio.get_event_loop().run_forever()
还是放吧,不然有一些比我还新手(如果下面评论有神马goeasy的推荐千万不要信,烧钱的东西,自己打个服务器才多少钱,还可以实现很多东西呢,它一年就收你几百几千的,鸭屎啦雷)
<!-- 请忽略我的html代码不正规 最重要快-->
<html>
<textarea id="response"></textarea>
<script>
var ws = new WebSocket('ws://localhost:6789')
ws.onopen=function () {
console.log('open')
}
ws.onclose=function () {
console.log('close')
}
ws.onmessage=function (e) {
response.innerHTML += e.data + '\n\r'
}
</script>
</html>
好了一切准备就绪
python运行这个文件python文件,连续开几个网页的时候另外一个网页的输入框会增加文字,你已经成功了!!!