socket编程
套接字,工作在传输层与应用层之间,通过TCP/UDP协议传输信息,分为客户端和服务端
模块:socket
使用步骤服务端
1.创建socket对象:soc = socket.socket()
2.绑定IP和端口:soc.bind((ip,port))
3.设置监听:soc.listen()
4.等待客户端连接:soc.accept()
客户端
1.创建socket对象:soc = socket.socket()
2.连接服务器:soc.connect((ip,port))公共方法
send() 发送消息
recv() 接收消息
import websocket
import json
###/Applications/Python\ 3.9/Install\ Certificates.command
class WebSockets():
def __init__(self, url):
self.url = url
self.ws = websocket.WebSocket()
self.ws.connect(url)
def send_ws(self,data):
self.ws.send(data)
res = self.ws.recv()
res1 = self.ws.recv()
print(res, res1)
if __name__ == '__main__':
ws = WebSockets(url='wss://localhost:8080/ws')
param_data = {
"token": "123456"
}
ws.send_ws(data=param_data)
ws.close()
import json
from ws4py.client.threadedclient import WebSocketClient
###/Applications/Python\ 3.9/Install\ Certificates.command
class CG_Client(WebSocketClient):
def opened(self):
req = '{"token": "123456"}'
self.send(req)
def closed(self, code, reason=None):
print("Closed down:",code,reason)
def received_message(self, res):
resp = json.loads(str(res))
# data = resp['data']
print("data:",resp)
if __name__ == '__main__':
ws = None
try:
ws = CG_Client("wss://localhost:8080/ws")
ws.connect()
ws.run_forever()
except KeyboardInterrupt:
ws.close()