pyhon服务器如何用websocke实现服务器和html5的通信(代码已实现成功连接客户端服务端)? 160C

服务端代码
#coding=gbk
#coding=utf-8
#-*- coding: UTF-8 -*
import struct
import socket
import re
import time
#ws握手响应头
import hashlib
import base64

from multiprocessing import Process
#HTML_ROOT_DIR = r"C:\Users\lenovo\Desktop\html"

def write_msg(message):
data=struct.pack('B',129)#写入第一个字节
msg_len=len(message)#写入包长度
if(msg_len<=125):
data+=struct.pack('B',msg_len)
elif(mas_len<=2**16-1):
data+=struct.pack('!BH',126,msg_len)
elif(mas_len<=2**64-1):
data+=struct.pack('!BQ',127,msg_len)
else:
pass
data+=bytes(message,encoding="utf-8")
return data

def handle_client(client_socket):
"""
处理客户端请求
"""
# 获取客户端请求数据
#获得key
request_data = client_socket.recv(1024)
print(request_data)
webpage_regex=re.compile('''.*Sec-WebSocket-Key:(.*)''',re.IGNORECASE)
key=webpage_regex.findall(request_data.decode("utf-8"))
keyy=''
try:
print(key[0])
keyy=key[0]
keyy=keyy.strip()
print(keyy)
except:
pass

# 打开文件,读取内容
try:
    file = open(r"C:\html\shouji\测试\客户端原生socket.html", "rb")
except IOError:
    response_start_line = "HTTP/1.1 404 Not Found\r\n"
    response_headers = "Server: My server\r\n"
    response_body = "The file is not found!"
    response = response_start_line + response_headers + "\r\n" + response_body
    client_socket.send(bytes(response, "utf-8"))
    client_socket.close()
else:
    file_data = file.read()
    file.close()

if(keyy==''):
    response_start_line = "HTTP/1.1 200 OK\r\n"
    response_headers = "Server: My server\r\n"
    response_body = file_data.decode("utf-8")
    response = response_start_line + response_headers + "\r\n" + response_body
    client_socket.send(bytes(response, "utf-8"))
    client_socket.close()
    print('https响应已发送')
else:
    magic = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
    sha1 = hashlib.sha1()
    sha1.update((keyy+magic).encode("utf8"))
    keyy=base64.b64encode(sha1.digest())
    print('dddddd',base64.b64encode(sha1.digest()))
    keyy=keyy.decode("utf8")
    print('***********************',keyy)
    response_start_line = "HTTP/1.1 101 Switching Protocols\r\n"
    response_headers = "Upgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept:"+keyy+"\r\n"
    response_body = file_data.decode("utf-8")
    response = response_start_line + response_headers + "\r\n" #+ response_body
    client_socket.send(bytes(response, "utf-8"))
    print('ws响应已发送')

    while(1):
        time.sleep(5)
        client_socket.send(bytes('dddd', "utf-8"))
        #client_socket.send( write_msg('www.baidu.com'))
        print('发送了一次')


# 关闭客户端连接
#client_socket.close()

if name == "__main__":
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(("0.0.0.0", 8000))
server_socket.listen(128)

while True:
    client_socket, client_address = server_socket.accept()
    print("[%s, %s]用户连接上了" % client_address)
    handle_client_process = Process(target=handle_client, args=(client_socket,))
    handle_client_process.start()
    #client_socket.close()


    客户端代码:
    <!DOCTYPE html>





史p 芬

var ws = new WebSocket("ws://127.0.0.1:8000/"); //document.write(Date()); ws.onopen = function(e) { // Check the protocol chosen by the server //console.log(echoSocket.protocol); alert('连接上了') document.write(Date()); //ws.send('已经连接') } // 接受文本消息的事件处理实例: ws.onmessage = function(e) { alert('接受到消息') if(typeof e.data === "string"){ console.log("String message received", e, e.data); } else { console.log("Other message received", e, e.data); } }; ws.onclose = function(e) { alert('连接关闭') console.log("Connection closed", e); };


2个回答

可以使用flask框架,有封装好的api.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐