python网络编程之socketio
服务端:
import socketio class ChatServer: def __init__(self): # 创建Socket.IO服务器实例 self.sio = socketio.Server(cors_allowed_origins='*') self.app = socketio.WSGIApp(self.sio) # 注册事件处理 self.sio.on('connect', self.handle_connect) self.sio.on('disconnect', self.handle_disconnect) self.sio.on('chat_message', self.handle_message) def handle_connect(self, sid, environ): print(f"用户 {sid} 已连接") #print(f"environ={environ}") #self.sio.emit('chat_message', {'user': '系统', 'message': f'用户 {sid} 已加入聊天'}, room=sid) def handle_disconnect(self, sid): print(f"用户 {sid} 已断开连接") #self.sio.emit('chat_message', {'user': '系统', 'message': f'用户 {sid} 已离开聊天'}) def handle_message(self, sid, data): print(f"用户 {sid} 发送消息: {data['message']}") # 广播消息给所有用户,群发 #sio.emit('my event', {'data': 'foobar'}) #给指定用户发送 user_sid = data['user_sid'] self.sio.emit('chat_message', {'user': sid, 'message': data['message']}, room=user_sid) def run(self, host='0.0.0.0', port=5000): import eventlet eventlet.wsgi.server(eventlet.listen((host, port)), self.app) # 启动服务器 if __name__ == '__main__': server = ChatServer() server.run() #https://blog.csdn.net/tangsiqi130/article/details/135407365 #https://zhuanlan.zhihu.com/p/658852864
客户端:
import socketio sio = socketio.Client() @sio.on('connect') def on_connect(): print('connection to server') @sio.on('chat_message') def chat_message(data): print('client receive:', data) @sio.on('disconnect') def disconnect(): print("Disconnected from server") sio.connect('http://127.0.0.1:5000') ''' print(sio.__dict__) print(dir(sio)) help(sio) ''' print('客户端id:'+sio.namespaces['/']) #sio.emit('chat_message', {'message': '测试ing'}) #sio.emit('chat_message', {'message': '发送给指定用户', room=user_sid) sio.wait()
html客户端:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Socket.IO 聊天室</title> </head> <body> <h1>聊天室</h1> <div id="messages"></div> <input id="message_input" placeholder="输入消息..."> <button onclick="sendMessage()">发送</button> <script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script> <script> const socket = io('http://localhost:5000'); socket.on('connect', () => { console.log('客户端id:'+socket.id); }); // 接收消息并展示 socket.on('chat_message', function(data) { const messageDiv = document.getElementById('messages'); const newMessage = document.createElement('p'); newMessage.textContent = `${data.user}: ${data.message}`; messageDiv.appendChild(newMessage); }); // 发送消息 function sendMessage() { const input = document.getElementById('message_input'); socket.emit('chat_message', {message: input.value, user_sid : 'zxIUKV-vO7_hvbwMAAAD'}); input.value = ''; } </script> </body> </html>
输出:
本文来自博客园,作者:河北大学-徐小波,转载请注明原文链接:https://www.cnblogs.com/xuxiaobo/p/18624940