用Python实现一个简易的WebSocket Server

#coding=utf-8from threading import Threadimport structimport timeimport hashlibimport base64import socketimport time class returnCrossDomain(Thread): def __init__(self,connection):
摘要由CSDN通过智能技术生成
</pre><pre name="code" class="python">#coding=utf-8

from threading import Thread
import struct
import time
import hashlib
import base64
import socket
import time  

class returnCrossDomain(Thread):  
    def __init__(self,connection):  
        Thread.__init__(self)  
        self.con = connection  
        self.isHandleShake = False  
    def run(self):  
        while True:  
            if not self.isHandleShake: 
                #开始握手阶段
                header = self.analyzeReq()
                secKey = header['Sec-WebSocket-Key'];  

                acceptKey = self.generateAcceptKey(secKey)

                response = "HTTP/1.1 101 Switching Protocols\r\n"  
                response += "Upgrade: websocket\r\n"  
                response += "Connection: Upgrade\r\n" 
                response += "Sec-WebSocket-Accept: %s\r\n
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 安装websocket-client和protobuf 首先需要安装websocket-client和protobuf两个库,可以使用pip进行安装: ``` pip install websocket-client protobuf ``` 2. 编写protobuf文件 定义一个简单的protobuf文件,名为`message.proto`,内容如下: ``` syntax = "proto3"; message Message { string content = 1; } ``` 然后使用`protoc`命令将其编译成Python代码: ``` protoc message.proto --python_out=. ``` 3. 编写客户端代码 使用websocket-client和protobuf库实现一个简单的客户端,连接到WebSocket服务器并发送和接收消息。 ```python import websocket import message_pb2 def on_open(ws): print('Connected to server') # 发送消息 message = message_pb2.Message() message.content = 'Hello, server!' ws.send(message.SerializeToString()) def on_message(ws, message): # 接收消息 message = message_pb2.Message() message.ParseFromString(message) print('Received message:', message.content) def on_close(ws): print('Disconnected from server') # 创建WebSocket连接 ws = websocket.WebSocketApp('ws://localhost:8000', on_open=on_open, on_message=on_message, on_close=on_close) # 开始监听WebSocket消息 ws.run_forever() ``` 4. 运行客户端 在命令行中运行客户端代码: ``` python client.py ``` 客户端将连接到WebSocket服务器并发送一条消息,然后等待接收服务器返回的消息。如果一切正常,客户端将输出类似以下内容: ``` Connected to server Received message: Hello, client! Disconnected from server ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值