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. js怎样实现在类似qq的联系人分组中进行搜索后,又可恢复原分组的界面?2. javascript - 百度地图一开始设置了中心点,怎么通过按钮在调转到对应的中心点????3. windows-server - 阿里云服务器给了权限,本地采集的数据远程写入服务器中MySQL5.5表中,一秒可以写入多少?这个速度一般由什么来决定?4. MongoDB的索引需要考虑每个键的索引方向,为何这么设计?而MySQL的索引则无需考虑方向,两者之间有何优劣势?5. javascript - 微信 H5 授权 返回键6. mysql优化 - mysql 一张表如果不能确保字段列长度一致,是不是就不需要用到char。7. python - 如何将文本文件的CR换行符换成LF换行符?8. 怎样用python给mp3添加封面?9. TP6里多应用里如何开启调试跟踪10. 数据库 - Mysql的存储过程真的是个坑!求助下面的存储过程哪里错啦,实在是找不到哪里的问题了。