AKor February 2016

Simple Python chat app with sockets

I'm trying to make a simple client/server chat app in Python with sockets, and eventually turn it into a networked game of Rock, Paper, Scissors.

I found a guide online to create the client/server but I'm having trouble modifying the loops so that each script listens for the other, receives a message, then shows a raw_input that becomes the message sent to the other script, then so on. Here's the code:

client.py

#!/usr/bin/python   

import socket           

s = socket.socket()        
host = socket.gethostname()
port = 12221             

s.connect((host, port))
while True:
    z = raw_input("Enter something for the server: ")
    s.send(z) 
    print s.recv(1024) 

server.py

#!/usr/bin/python          

import socket         

s = socket.socket()        
host = socket.gethostname() 
port = 12221               
s.bind((host, port))   

s.listen(5)

while True:
   c, addr = s.accept()
   print 'Got connection from', addr
   print c.recv(1024)
   q = raw_input("Enter something to this client: ")
   c.send(q)             

Any help? Thank you.

Answers


cricket_007 February 2016

Like @DavidCullen said in the comments, you are halting on the second time through the while loop for the server to accept a new connection.

You can get around that by doing an if-connected check. I also added some print statements so you could clearly debug what is happening.

server.py

#!/usr/bin/python

import socket

s = socket.socket()
host = socket.gethostname()
port = 12221
s.bind((host, port))

s.listen(5)
c = None

while True:
   if c is None:
       # Halts
       print '[Waiting for connection...]'
       c, addr = s.accept()
       print 'Got connection from', addr
   else:
       # Halts
       print '[Waiting for response...]'
       print c.recv(1024)
       q = raw_input("Enter something to this client: ")
       c.send(q)

client.py

#!/usr/bin/python

import socket

s = socket.socket()
host = socket.gethostname()
port = 12221

s.connect((host, port))
print 'Connected to', host

while True:
    z = raw_input("Enter something for the server: ")
    s.send(z)
    # Halts
    print '[Waiting for response...]'
    print s.recv(1024)

Post Status

Asked in February 2016
Viewed 3,497 times
Voted 12
Answered 1 times

Search




Leave an answer