python安装websocket
发布时间: 2023-09-24 21:56:51
‘壹’ 请问各位大大,python如何编写websocket的服务端和客户端,wss的那种
安装dwebsocket(pip install dwebsocket ) 后参考下面的链接
我django 2.0 测试通过
网页链接
‘贰’ python怎么连接websocket
以下有一个例子,是基于python27版本的,先要pip安装websocket-client。
大概流程如下,具体的传输的数据,还是要知道client和server之间的消息通讯规定,改成自己需要的
#-*-encoding:utf-8-*-
importsys
fromsocketimport*
importjson,time,threading
fromwebsocketimportcreate_connection
reload(sys)
sys.setdefaultencoding("utf8")
#config={
#'HOST':'127.0.0.1',
#'PORT':10086
#}
#pipinstallwebsocket-client
classClient():
def__init__(self):
#调用create_connection方法,建立一个websocket链接
#链接地址请修改成你自己需要的
self.ws=create_connection("ws://47.93.91.89:10086/name/hehe")
#建一个线程,监听服务器发送给客户端的数据
self.trecv=threading.Thread(target=self.recv)
self.trecv.start()
#发送方法,聊天输入语句时调用,此处默认为群聊ALL
defsend(self,content):
#这里定义的消息体要换成你自己的消息体,变成你需要的。
msg={
"type":"POST",
"username":"hehe",
"sendto":"ALL",
"content":content
}
msg=json.mps(msg)
self.ws.send(msg)
#接收服务端发送给客户的数据,只要ws处于连接状态,则一直接收数据
defrecv(self):
try:
whileself.ws.connected:
result=self.ws.recv()
print"receivedmsg:"+str(result)
exceptException,e:
pass
#关闭时,发送QUIT方法,退出ws链接
defclose(self):
#具体要知道你自己退出链接的消息体是什么,如果没有,可以不写这个方法
msg={
"type":"QUIT",
"username":"johanna",
"content":"byebye,everyone"
}
msg=json.mps(msg)
self.ws.send(msg)
if__name__=='__main__':
c=Client()
#当输入非exit时,则持续ws链接状态,如果exit,则关闭链接
whileTrue:
content=raw_input("pleaseinput(inputexittoexit):")
ifcontent=="exit":
c.close()
break
else:
c.send(content)
time.sleep(1)
‘叁’ python怎么连接websocket
websocket是html5引入的一个新特性,传统的web应用是通过http协议来提供支持,如果要实时同步传输数据,需要轮询,效率低下
websocket是类似socket通信,web端连接服务器后,握手成功,一直保持连接,可以理解为长连接,这时服务器就可以主动给客户端发送数据,实现数据的自动更新。
使用websocket需要注意浏览器和当前的版本,不同的浏览器提供的支持不一样,因此设计服务器的时候,需要考虑。
‘肆’ python怎么连接websocket
如果只是模拟js端发送接收的话,已经有了websocket server的话,只有client就好了
pip install websocket-client
websocket_client.py(客户端)
#-*-encoding:utf-8-*-
importsys
sys.path.append("..")
fromsocketimport*
importjson,time,threading
fromwebsocketimportcreate_connection
reload(sys)
sys.setdefaultencoding("utf8")
#config={
#'HOST':'127.0.0.1',
#'PORT':10010
#}
#pipinstallwebsocket-client
classClient():
def__init__(self):
#调用create_connection方法,建立一个websocket链接,链接是自己的链接
self.ws=create_connection("ws://127.0.0.1:10010/xxxx")
#建一个线程,监听服务器发送给客户端的数据
self.trecv=threading.Thread(target=self.recv)
self.trecv.start()
#发送方法,聊天输入语句时调用,此处默认为群聊ALL
defsend(self,content):
#这里的msg要根据实际需要自己写
msg={
"type":"POST",
"content":content
}
msg=json.mps(msg)
self.ws.send(msg)
#接收服务端发送给客户的数据,只要ws处于连接状态,则一直接收数据
defrecv(self):
try:
whileself.ws.connected:
result=self.ws.recv()
print"receivedmsg:"+str(result)
exceptException,e:
pass
if__name__=='__main__':
c=Client()
#建立链接后,就可以按照需要自己send了
c.send(content)
热点内容