我正在使用套接字模块在Python中编写多线程套接字应用程序。 服务器侦听连接,当它获得连接时,它会为该套接字生成一个线程。
服务器线程将一些数据发送到客户端。但客户尚未准备好接收它。我以为这会导致服务器等到客户端启动recv但是立即返回
然后客户端调用阻塞的recv,并且没有收到任何数据。
客户端套接字构造函数
self.__clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.__clientSocket.connect((server, port))
服务器套接字构造函数
self.servSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.servSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#self.servSock.settimeout(None)
self.servSock.setblocking(1)
self.servSock.bind((self.addr,self.port))
self.servSock.listen(5)
听取接受线程
try:
(cs, address) = self.servSock.accept()
except socket.timeout:
return
threadName = '\r\nClient %s:%s\r\n' % (cs, address)
print threadName
clientSocketHandler = ClientSocket()
clientSocketHandler.setClientSocket(cs)
self.clients.newThread(self.clientFunc, {clientSocketHandler : "1"}, threadName).start()
服务器和客户端从ClientSocket内部发送/ rec方法
receivedData = self.__clientSocket.recv(1024*1024)
self.__clientSocket.send(s)
为什么send()会立即返回?
答案 0 :(得分:4)
为什么send()会立即返回?
所有send()都填充网络缓冲区并返回发送的字节数。
如果您希望发送阻止只是从客户端收回确认消息。
答案 1 :(得分:1)
客户端不必准备接收数据 - 数据将在套接字的接收缓冲区中排队,直到您准备好recv()它为止。由于发送缓冲区未满,发送立即返回 - 如果已满,send()将阻塞,直到您想要发送的数据有空间。
大部分时间你都不会填写它 - 因此你正在经历的事情。另一方面,你可能不希望在其中使用1024 * 1024的recv调用 - 这有点偏高。
答案 2 :(得分:1)
很抱歉我在提出这个问题后不久就解决了这个问题。 @Lee感谢您的回答,它指出了我正确的方向。 解决方案是发送一个4byte int,指定要遵循的数据大小。客户端总是会收到这四个字节,然后是数据的大小。
from commandClass import Command
from commandActionClass import CommandAction
import socket
from time import *
import struct
class ClientSocket():
instance = None
__connected = False
__clientSocket = None
@staticmethod
def getInstance():
if ClientSocket.instance == None:
ClientSocket.instance = ClientSocket()
return ClientSocket.instance
def __init__(self):
self.__connected = False
self.receivedData = ''
self.bufSize = 4096
self.buffer = ''
def connect(self, server, port):
if self.isConnected():
raise Exception('Already connected.')
self.__clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.__clientSocket.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
self.__clientSocket.connect((server, port))
self.__clientSocket.setblocking(1)
self.__connected = True
def disconnect(self):
try:
self.receivedData = ''
self.buffer = ''
self.__clientSocket.close()
except Exception, e:
print e
finally:
self.__connected = False
def sendString(self,s):
try:
if (self.isConnected()):
self.__clientSocket.send(s)
except Exception, e:
print e
self.disconnect()
def __pop(self, size):
data = self.receivedData[:size]
self.receivedData = self.receivedData[size:]
return data
def __recv(self,toRead):
self.flush()
while ((len(self.receivedData)<toRead)and(self.isConnected())):
data = self.__clientSocket.recv(self.bufSize)
if not data:
self.disconnect()
self.receivedData = self.receivedData + data
return self.__pop(toRead)
def __sendint(self, x):
self.__sendall(struct.pack("i", x))
def __recvint(self):
data = self.__recv(4)
if not data:
raise Exception('Expected to receive buffer size')
return struct.unpack("i", data)[0]
def flush(self):
if len(self.buffer)>0:
self.__clientSocket.sendall(self.buffer)
self.buffer = ''
def __sendall(self, s):
self.buffer = self.buffer + s
def send(self,s):
try:
if (not self.isConnected()):
raise Exception('Socket is not connected')
data = s.pickle()
self.__sendint(len(data))
self.__sendall(data)
except Exception, e:
self.disconnect()
raise e
def sendEOC(self):
self.send(Command(CommandAction.EOC, time()))#send our system time. can be used for ping
def receive(self):
if (not self.isConnected()):
raise Exception('Socket Error. Not Connected')
try:
#first receive the size of packet
buffsize = self.__recvint()
#now receive the actual data
data = self.__recv(buffsize)
if not data:
raise Exception('No data to receive')
command = Command.unpickle(data)
except Exception, e:
self.disconnect()
command = Command(CommandAction.Invalid, None)
raise e
#finally?
return command
def isConnected(self):
return self.__connected
def setClientSocket(self, clientSocket):
self.__clientSocket = clientSocket
self.__connected = True #assume its connected