By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,818 Members | 1,313 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,818 IT Pros & Developers. It's quick & easy.

Socket flushing

P: 1
I am new to python, and I am trying to send a message over a TCP socket to another component (client). I have to send the message in chunks of 1024 bytes in response to client REQ.

The problem is that when first chunk of 1024 bytes is received by the client, it contains a character string appended at the end from the Initial Message that the client had sent as REQ.

What can I do to flush the socket connection before delivering the messsage

my setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)


Apr 3 '08 #1
Share this Question
Share on Google+
1 Reply

P: 87
I'm not really sure what your problem is here, because I have never had it. If you post code, that would be most helpful. Anyway, for sockets, I would do something like this:
Expand|Select|Wrap|Line Numbers
  1. import socket
  3. BUFF_SIZE=1024
  4. REQUEST_SIZE=1024
  6. class my_sock(socket.socket):
  7.     def __init__(self,*args,**kwds):
  8.         self.buffer=""
  9.         socket.socket.__init__(self,*args,**kwds)
  10.     def send(self,data):
  11.         self.buffer+=data
  12.         while BUFF_SIZE<len(self.buffer): # I am biased against > symbols
  13.             socket.socket.send(self,self.buffer[:BUFF_SIZE])
  14.             self.buffer=self.buffer[BUFF_SIZE:]
  15.     def flush(self):
  16.         self.buffer+=(BUFFER_SIZE-len(self.buffer)%BUFFER_SIZE)*"\x00"
  17.         self.send("")
  19. sock=my_sock()
  20. sock.bind(("",80)) # (address, port)
  21. sock.listen(1)
  22. while True:
  23.     s=sock.accept()
  24.     try:
  25.         data=s.recv(REQUEST_SIZE)
  26.         if data.startswith("This is an evil request for spam and eggs."):
  27.             s.send("No, it isn't. Spam isn't on the menu. Unless, of course, you get it with spam, spam, spam, spam, spam, spam, baked beans, spam, spam, spam, and spam.")
  28.             s.flush()
  29.     finally: # just in case something goes wrong, don't leave the socket open
  30.         s.close()
I haven't tested it, so I can't guarantee that it works, but that should be a start.
Apr 11 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.