user1205371
user1205371

Reputation:

Client server communication via sockets within same file/program in Python?

I need to make a program that communicates within the same program back and forth between client and server, but after following the instructions on: http://woozle.org/~neale/papers/sockets.html it just keeps listening and I see nothing printed.

How do I enable basic client server functionality within the same file?

#!/usr/bin/python           # This is server.py file
import socket               # Import socket module
import random
import os
import time as t

#open socket
s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = random.randint(0,65535)                # Reserve a port for your service.

if os.fork() == 0:
   #server
   s.listen(1)
   print 'about to listen'
   while 1:
      c = s.accept()
      cli_sock, cli_addr = c
      cli_sock.send("Hello to you! %s" % cli_addr)
elif os.fork() == 0:
   t.sleep(1)
   #client
   print 'in here2'
   s.bind((host, port))        # Bind to the port
   s.connect((host,port))
   s.send("Hello!\n")
   print s.recv(8192)
   s.close()

Upvotes: 1

Views: 1516

Answers (1)

Silas Ray
Silas Ray

Reputation: 26150

You're never going to hit your client code, as you enter an infinite loop right after starting the listener. For a toy example like this, you'll need to create 2 socket objects, one for the server and one for the client, then pingpong back and forth between them within your code; you can't use a serve forever style loop like you are here unless it runs in a parallel thread/process so you don't block execution of the main thread.

Upvotes: 2

Related Questions