tags:

views:

33

answers:

2

i have a socket client and a socket server.

(the server is in python, and is synchroneous.)

sometimes the clients send an empty string. i'm required to identify this situation, and return a response.

with this code, the server just keeps on waiting, and the client's don't get anything in return, unless it sends something mroe "fat" ;)

how can i capture the empty message? is it at all possible?

that's my server code:

import SocketServer

def multi_threaded_socket_server():

    class MyRequestHandler(SocketServer.BaseRequestHandler):
        def handle(self):
            while True:
                print 'waiting for client calls...'
                received = self.request.recv( PACKET_SIZE )
                (handle request... )
+1  A: 

If the empty string means 0 bytes, the socket library on the client side might ignore it because a packet with 0 data bytes is a disconnect packet.

deltreme
A: 

Assuming TCP, you have to design a protocol that indicates when you've received a complete message. send() is not guaranteed to send every byte (check the return value) and recv() is not guaranteed to read the number of bytes requested.

Design a protocol that includes a way to determine a complete message has been received. Common ways are to send the size of the message first, or use a special sequence at the end indicating the message is complete. Also note socket's sendall() method will send all the bytes of the message.

Examples:

sendall('\x05Hello')  # length first
sendall('Hello\x00')  # nul-termination

For receiving, buffer recv() calls until a complete message is present.

Receive Algorithm (non-working code):

class Handler:

  def __init__(self):
    self.buffer = ''

  def handler(self):
    while True:
      msg = self.get_msg()
      if not msg: break
      process msg

  def get_msg(self):
    if complete message not at the beginning of buffer:
      chunk = recv(1000)
      if not chunk: return '' # socket closed
      buffer += chunk
    remove message from beginning of buffer...update buffer
    return message
Mark Tolonen