socket編程 - python如何進(jìn)行socket連接
問(wèn)題描述
嘗試連接 119.23.124.81:7575
服務(wù)器每5秒會(huì)返回一個(gè){'type':'ping'},我嘗試用以下代碼去連接,但是無(wú)法獲取到這個(gè){'type':'ping'}:
s = socket(AF_INET, SOCK_STREAM)# 建立連接:s.connect((’119.23.124.81’, 7575))while True: print(s.recv(1024).decode(’utf-8’))s.close()
代碼不會(huì)報(bào)錯(cuò),但是也獲取到我想要的內(nèi)容
請(qǐng)問(wèn)要如何寫(xiě)才能獲取到這個(gè){'type':'ping'}
問(wèn)題解答
回答1:搞清楚了,原來(lái)這個(gè)是使用的websocket協(xié)議,不是普通的socket
換用websocket這個(gè)庫(kù)就好了,代碼如下:
from websocket import create_connectionws = create_connection('ws://42.96.131.185:7575')print('Sending ’Hello, World’...')for i in range(10000): ws.send(b'Hello, World') print('Sent')print('Reeiving...')result = ws.recv()print('Received ’%s’' % result)ws.close()回答2:
參考官方文檔
# Echo server programimport socketHOST = ’’ # Symbolic name meaning all available interfacesPORT = 50007 # Arbitrary non-privileged ports = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.bind((HOST, PORT))s.listen(1)conn, addr = s.accept()print ’Connected by’, addrwhile 1: data = conn.recv(1024) if not data: breakconn.sendall(data)conn.close()
and
import SocketServerclass MyTCPHandler(SocketServer.BaseRequestHandler):'''The request handler class for our server.It is instantiated once per connection to the server, and mustoverride the handle() method to implement communication to theclient.''' def handle(self):# self.request is the TCP socket connected to the clientself.data = self.request.recv(1024).strip()print '{} wrote:'.format(self.client_address[0])print self.data# just send back the same data, but upper-casedself.request.sendall(self.data.upper())if __name__ == '__main__': HOST, PORT = 'localhost', 9999 # Create the server, binding to localhost on port 9999 server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler) # Activate the server; this will keep running until you # interrupt the program with Ctrl-C server.serve_forever()回答3:
因?yàn)槟惆l(fā)送的數(shù)據(jù)是一個(gè)字典對(duì)象,所以在socket發(fā)送據(jù)時(shí),用pickle或者json模塊對(duì)數(shù)據(jù)進(jìn)行序列化再發(fā)送,對(duì)應(yīng)的,接收端要用pickle或者json進(jìn)行反序列化操作。
相關(guān)文章:
1. javascript - sublime快鍵鍵問(wèn)題2. javascript - immutable配合react提升性能?3. css - 寫(xiě)頁(yè)面遇到個(gè)布局問(wèn)題,求大佬們幫解答,在線等,急!~4. javascript - nodejs關(guān)于進(jìn)程間發(fā)送句柄的一點(diǎn)疑問(wèn)5. Apache 已經(jīng)把網(wǎng)站根目錄的改為allow from all了,但是服務(wù)器還是不能訪問(wèn)?6. 實(shí)現(xiàn)bing搜索工具urlAPI提交7. 配置Apache時(shí),添加對(duì)PHP的支持時(shí)語(yǔ)法錯(cuò)誤8. vue.js - Vue 如何像Angular.js watch 一樣監(jiān)聽(tīng)數(shù)據(jù)變化9. javascript - 移動(dòng)端上不能實(shí)現(xiàn)拖拽布局嗎?10. phpstudy8.1支持win11系統(tǒng)嗎?

網(wǎng)公網(wǎng)安備