Nickolouse
Nickolouse

Reputation: 301

Connection refused with python sockets

So I am trying to make a server program that will call the client program. The server client work fine if I call them myself from the command line but the connection is refused when the server calls it. Why is this not working?

This is the server code:

import socket,os

s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
    os.remove("/tmp/SocketTest")
except OSError:
    pass
s.bind("/tmp/SocketTest")
os.system("python compute.py")#compute is the client
#execfile('compute.py')
s.listen(1)
conn, addr = s.accept()
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.send(data)
conn.close()

This is the client code:

import socket

s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect("/tmp/SocketTest")
s.send('Hello, world \n')
s.send('its a mighty fine day')
data = s.recv(1024)
s.close()
print 'Received', repr(data)

Upvotes: 1

Views: 1793

Answers (2)

Savir
Savir

Reputation: 18418

I think the error is that you're calling compute.py before calling listen.

os.system will block your server until the call to python compute.py is completed.

Try subprocess.Popen to spawn the call to compute.py in parallel to your server in a non blocking manner. Callingsubprocess.Popen will launch python compute.py in a new process, and will continue executing the next line conn, addr = s.accept() )

#!/usr/bin/env python

import socket
import os
import subprocess

s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
    os.remove("/tmp/SocketTest")
except OSError:
    pass
s.bind("/tmp/SocketTest")
s.listen(1)
sp = subprocess.Popen(["/usr/bin/env", "python", "compute.py"])
conn, addr = s.accept()
while 1:
    data = conn.recv(1024)
    if not data:
        break
    conn.send(data)
conn.close()

That outputs:

Received 'Hello, world \nits a mighty fine day'

Upvotes: 0

icktoofay
icktoofay

Reputation: 128993

os.system will run the command you give it to completion, and you’re doing this before you call listen. As such, the client will try to connect to the server before it’s listening. Only once the client exits will the server move on past that line of code to actually start listening and accepting connections.

What you probably want to do is after the call to listen, but before the call to accept (which is when you start blocking), use subprocess.Popen to spawn a subprocess and do not wait on it.

Upvotes: 2

Related Questions