python websocket
页面
<!DOCTYPE html>
<html>
<head>
<title>WebSocket</title>
<style>
html, body {
font: normal 0.9em arial, helvetica;
}
#log {
width: 440px;
height: 200px;
border: 1px solid #7F9DB9;
overflow: auto;
}
#msg {
width: 330px;
}
</style>
<script>
var socket;
function init() {
var host = "ws://127.0.0.1:1234/";
try {
socket = new WebSocket(host);
socket.onopen = function (msg) {
;
};
socket.onmessage = function (msg) {
log(msg.data);
};
socket.onclose = function (msg) {
log("Lose Connection!");
};
}
catch (ex) {
log(ex);
}
$("msg").focus();
}
function send() {
var txt, msg;
txt = $("msg");
msg = txt.value;
if (!msg) {
alert("Message can not be empty");
return;
}
txt.value = "";
txt.focus();
try {
socket.send(msg);
} catch (ex) {
log(ex);
}
}
window.onbeforeunload = function () {
try {
socket.send('quit');
socket.close();
socket = null;
}
catch (ex) {
log(ex);
}
};
function $(id) {
return document.getElementById(id);
}
function log(msg) {
$("log").innerHTML += "<br>" + msg;
}
function onkey(event) {
if (event.keyCode == 13) {
send();
}
}
</script>
</head>
<body onload="init()">
<h3>WebSocket</h3>
<br><br>
<div id="log"></div>
<input id="msg" type="textbox" onkeypress="onkey(event)"/>
<button onclick="send()">发送</button>
</body>
</html>web服务端
import struct,socket
import hashlib
import threading,random
from base64 import b64encode, b64decode
connectionlist = {}
def sendMessage(message):
global connectionlist
for connection in connectionlist.values():
connection.send(str.encode("\x00%s\xFF" % message))
def deleteconnection(item):
global connectionlist
del connectionlist['connection'+item]
class WebSocket(threading.Thread):
GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
def __init__(self,conn,index,name,remote, path="/"):
threading.Thread.__init__(self)
self.conn = conn
self.index = index
self.name = name
self.remote = remote
self.path = path
self.buffer = ""
def run(self):
print('Socket%s Start!' % self.index)
headers = {}
self.handshaken = False
while True:
if self.handshaken == False:
print ('Socket%s Start Handshaken with %s!' % (self.index,self.remote))
self.buffer += bytes.decode(self.conn.recv(1024))
if self.buffer.find('\r\n\r\n') != -1:
header, data = self.buffer.split('\r\n\r\n', 1)
for line in header.split("\r\n")[1:]:
key, value = line.split(": ", 1)
headers[key] = value
headers["Location"] = ("ws://%s%s" %(headers["Host"], self.path))
key = headers['Sec-WebSocket-Key']
token = b64encode(hashlib.sha1(str.encode(key + self.GUID)).digest())
handshake="HTTP/1.1 101 Switching Protocols\r\n"\
"Upgrade: websocket\r\n"\
"Connection: Upgrade\r\n"\
"Sec-WebSocket-Accept: "+bytes.decode(token)+"\r\n"\
"WebSocket-Origin: "+str(headers["Origin"])+"\r\n"\
"WebSocket-Location: "+str(headers["Location"])+"\r\n\r\n"
self.conn.send(str.encode(handshake))
self.handshaken = True
print ('Socket %s Handshaken with %s success!' %(self.index, self.remote))
sendMessage('Welcome, ' + self.name + ' !')
else:
mm=self.conn.recv(64)
print(mm.decode('utf-8', 'ignore'))
self.buffer +=mm.decode('utf-8', 'ignore')
if self.buffer.find("\xFF")!=-1:
s = self.buffer.split("\xFF")[0][1:]
if s=='quit':
print ('Socket%s Logout!' % (self.index))
sendMessage(self.name+' Logout')
deleteconnection(str(self.index))
self.conn.close()
break
else:
print ('Socket%s Got msg:%s from %s!' % (self.index,s,self.remote))
sendMessage(self.name+':'+s)
self.buffer = ""
class WebSocketServer(object):
def __init__(self):
self.socket = None
def begin(self):
print( 'WebSocketServer Start!')
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind(("127.0.0.1",1234))
self.socket.listen(50)
global connectionlist
i=0
while True:
connection, address = self.socket.accept()
username=address[0]
newSocket = WebSocket(connection,i,username,address)
newSocket.start()
connectionlist['connection'+str(i)]=connection
i = i + 1
if __name__ == "__main__":
server = WebSocketServer()
server.begin()说下配置 ,python3.4,websocket 13
无法模拟 服务器,希望有大神帮小弟解答下
相关推荐
websocket Server Python实现
python websocket server javascript websocket client
python之WebSocket的开发
## websocket.py import socket import struct import hashlib,base64 import threading,random #线程,套接字,哈希表,随机数 #存放链接客户fd,元组 connectionlist = {} #发送指定的消息 def sendMessage(message): #对全局变量的引用 global conn
Python如何爬取实时变化的WebSocket数据的方法
主要介绍了Python如何爬取实时变化的WebSocket数据的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
用Python进行websocket接口测试
我们在做接口测试时,除了常见的http接口,还有一种比较多见,就是socket接口,今天讲解下怎么用Python进行websocket接口测试。 现在大多数用的都是websocket,那我们就先来安装一下websocket的安装包。 pip install websocket-client 安装完之后,我们就开始我们的websocket之旅了。 我们先来看个炒鸡简单的栗子: import websocket ws = websocket.WebSocket() ws.connect("ws://example.com/websocket", http_proxy_host=
websocket-client:适用于Python的WebSocket客户端
websocket客户端 websocket-client模块是Python的WebSocket客户端。 它提供对WebSockets的低级API的访问。 所有API均用于同步功能。 websocket-client仅支持 。 执照 BSD 文献资料 该项目的文档可在找到 贡献 请在查看贡献准则。 安装 首先,安装以下依赖项: 六 适用于Python 2.x的backports.ssl_match_hostname 您可以使用以下命令安装依赖项: pip install six和pip install backports.ssl_match_hostname 您可以使用python s


