socket編程 - python如何進行socket連接
問題描述
嘗試連接 119.23.124.81:7575
服務器每5秒會返回一個{'type':'ping'},我嘗試用以下代碼去連接,但是無法獲取到這個{'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()
代碼不會報錯,但是也獲取到我想要的內容
請問要如何寫才能獲取到這個{'type':'ping'}
問題解答
回答1:搞清楚了,原來這個是使用的websocket協議,不是普通的socket
換用websocket這個庫就好了,代碼如下:
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:
因為你發送的數據是一個字典對象,所以在socket發送據時,用pickle或者json模塊對數據進行序列化再發送,對應的,接收端要用pickle或者json進行反序列化操作。
相關文章:
1. mysql 查詢身份證號字段值有效的數據2. javascript - ios返回不執行js怎么解決?3. 視頻文件不能播放,怎么辦?4. javascript - angular使從elastichearch中取出的文本高亮顯示,如圖所示5. python - 爬蟲模擬登錄后,爬取csdn后臺文章列表遇到的問題6. python bottle跑起來以后,定時執行的任務為什么每次都重復(多)執行一次?7. mysql - 分庫分表、分區、讀寫分離 這些都是用在什么場景下 ,會帶來哪些效率或者其他方面的好處8. javascript - 求幫助 , ATOM不顯示界面!!!!9. javascript - 移動端自適應10. html5 - HTML代碼中的文字亂碼是怎么回事?
