1

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) 
1
  • Your client cannot connect until you call listen or accept on the socket - but you call your client program before those lines on your server program. Your server will also sit and wait for your client to finish before continuing beyond the os.system call - probably not what you want. Commented Dec 7, 2014 at 23:26

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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' 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.