python如何进行socket连接

发布于 2022-09-04 15:01:56 字数 390 浏览 15 评论 0

尝试连接 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"}


如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

攒眉千度 2022-09-11 15:01:56

搞清楚了,原来这个是使用的websocket协议,不是普通的socket

换用websocket这个库就好了,代码如下:

from websocket import create_connection


ws = 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()
握住你手 2022-09-11 15:01:56

参考官方文档


# Echo server program
import socket

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
conn.sendall(data)
conn.close()

and


import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The request handler class for our server.

It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print "{} wrote:".format(self.client_address[0])
        print self.data
        # just send back the same data, but upper-cased
        self.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()
一紙繁鸢 2022-09-11 15:01:56

因为你发送的数据是一个字典对象,所以在socket发送据时,用pickle或者json模块对数据进行序列化再发送,对应的,接收端要用pickle或者json进行反序列化操作。

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文