1
votes

I have a problem here with this code. I'm opening a socket, then listening to it with a while loop. I send data from a php script with

socket_write($sock, $test, $len);

It works very well, but when I send several writes in a row, the Python script handles some of the writes as just one write.

import socket

HOST = 'localhost' # the host
PORT = 12126 # the port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
while 1:
  s.listen(0)
  conn, addr = s.accept()
  print 'Connected by', addr
  while 1:
      data = conn.recv(1024)
      if not data: break
conn.close()

I'm looking for a way to listen to that port and get one write after another.

2
Yes I can print and see them in the Python program. - user1301036

2 Answers

3
votes

That's not the way sockets work. Bytes go in and bytes come out, but there has to be some other mechanism to tell you how big a message is. If you send 50 bytes, then another 75 bytes, then 20 bytes on one end of a socket, and then call recv(100), you could get anywhere from 1 to 100 bytes from a blocking socket. You are responsible for buffering recv's until you have a complete message, and you have to define what a complete message is. Some options:

  1. Send fixed length messages.
  2. Send a fixed number of bytes representing the length of the message, then the message.
  3. Separate messages with a sentinel byte.

Here's an example of a class to buffer received data using a sentinel byte:

import socket

class Client(object):

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

    def connect(self,address):
        self.buffer = ''
        self.sock = socket.socket()
        self.sock.connect(address)

    def get_msg(self):
        '''Append raw data to buffer until sentinel is found,
           then strip off the message, leaving the remainder
           in the buffer.
        '''
        while not '\n' in self.buffer:
            data = self.sock.recv(4096)
            if not data:
                return ''
            self.buffer += data
        sentinel = self.buffer.index('\n') + 1
        msg,self.buffer = self.buffer[:sentinel],self.buffer[sentinel:]
        return msg

    def close(self):
        self.sock.close()

if __name__ == '__main__':
    c = Client()
    c.connect((HOST,PORT))
    while True:
        msg = c.get_msg()
        if not msg:
            break
        print repr(msg)
    c.close()
1
votes

I don't think that's how unix sockets work. The recv system call can return however much data it wants, potentially batching messages in the buffer together. http://linux.die.net/man/2/recv

The typical way to achieve what you want is to use a protocol with delimiters between each message. HTTP and SMTP, for example, use newlines to separate each portion of a message.

In python, you could use something like this:

for message in data.split('\n'):
    do_stuff(message)

http://docs.python.org/howto/sockets.html