我正在创建一个套接字客户端并尝试获取一些数据.为了做到这一点,我需要通过套接字连接到Web服务器,服务器实际上创建了另一个套接字,它监听并等待数据,然后发送回客户端.
我对下面的代码的问题是我的套接字客户端不等待来自服务器的传入数据,只接受空数据.
我的代码:
import sys
import json
import socketIO_client
import time
host = 'https://SOME_URL'
socketIO = socketIO_client.SocketIO(host,params={"email" : "edmund@gmail.com"})
def on_connect(*args):
print "socket.io connected"
def on_disconnect(*args):
print "socketIO diconnected"
socketIO.on('connect',on_connect)
socketIO.on('disconnect',on_disconnect)
def on_response_state(*args):
print args # Prints ()
socketIO.emit('receive_state',on_response_state)
socketIO.wait_for_callbacks(seconds=3)
最佳答案
这是使用套接字的示例.使用s.accept(),客户端将等待客户端接受连接,然后再启动while循环以接收数据.这应该有助于解决您的问题.
def receiver():
PORT = 123
CHUNK_SIZE = 1024
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind(('0.0.0.0',PORT))
s.listen(1)
conn,address=s.accept() # accept an incoming connection using accept() method which will block until a new client connects
while True:
datachunk = conn.recv(CHUNK_SIZE) # reads data chunk from the socket in batches using method recv() until it returns an empty string
if not datachunk:
break # no more data coming in,so break out of the while loop
data.append(datachunk) # add chunk to your already collected data
conn.close()
print(data)
return
receiver()