0

I have a python script to receive strings send by netcat. It works when i have 1 client sending strings, but a second can't connect.

import socket

HOST = 'localhost'   # use '' to expose to all networks
PORT = 12345

def incoming(host, port):
  """Open specified port and return file-like object"""
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  # set SOL_SOCKET.SO_REUSEADDR=1 to reuse the socket if
  # needed later without waiting for timeout (after it is
  # closed, for example)
  sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  sock.bind((host, port))
  sock.listen(0)   # do not queue connections
  request, addr = sock.accept()
  return request.makefile('r', 0)
# /-- network ---


for line in incoming(HOST, PORT):
  print line,

I send strings from 2 clients to this script, but when the second client starts sending the connection gets interrupted. Is it possible to allow more than 1 simultaneous connection?

Changing the sock.listen() to a bigger number doesn't help

1 Answer 1

1

You're only accepting one connection. Furthermore, I find it weird that you'd like to dup the file descriptor and read of it as you do now. So, why don't you try something like this instead: yield incoming request and throw StopIteration when timed out, and as a bonus, use recv instead

import socket

HOST = 'localhost'   # use '' to expose to all networks
PORT = 12345

def incoming(host, port):
    """Open specified port and yield requests"""
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.settimeout(10)
    sock.bind((host, port))
    sock.listen(0)
    try:
        while True:
            request, addr = sock.accept()
            yield request
            request.close()
    except socket.timeout:
        raise StopIteration
    finally:
        sock.close()

for request in incoming(HOST, PORT):
    print request.recv(1024)
Sign up to request clarification or add additional context in comments.

2 Comments

I want to receive the strings continuously. With this script i have to restart the connection every time i want to send somthing
So just dont close the sockets in the function incoming and keep and use the sockets for as long as you want to use them. This solves the problem of accepting multiple connections. How you then use the sockets afterwards is up to you. I'd suggest collecting them and running select/poll/epoll to detect read events if you want to simply print out everything received.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.