cari

Rumah  >  Soal Jawab  >  teks badan

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"}


巴扎黑巴扎黑2872 hari yang lalu717

membalas semua(3)saya akan balas

  • 大家讲道理

    大家讲道理2017-04-18 10:27:11

    Saya dapat tahu, ternyata ini adalah protokol websocket yang digunakan, bukan soket biasa

    Hanya gunakan perpustakaan websocket sebagai gantinya

    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()

    balas
    0
  • 迷茫

    迷茫2017-04-18 10:27:11

    Rujuk dokumentasi rasmi

    
    # 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()
    

    dan

    
    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()

    balas
    0
  • PHP中文网

    PHP中文网2017-04-18 10:27:11

    Oleh kerana data yang anda hantar ialah objek kamus, apabila menghantar data melalui soket, gunakan modul pickle atau json untuk mensirikan data sebelum menghantarnya. Sejajar dengan itu, hujung penerima mesti menggunakan pickle atau json untuk penyahserilan.

    balas
    0
  • Batalbalas