A simple Python chat application with sockets

I am trying to create a simple Python client / server chat application with sockets and ultimately turn it into a Rock, Paper, Scissors network game.

I found a guide for creating a client / server, but I had problems with changing the loops, so that each script listens for another, receives a message, and then shows raw_input, which becomes a message sent to another script, then so on. Here is 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? Thanks.

+4
source share
1 answer

Like @DavidCullen in the comments, you stop a second time through the while loop so the server can accept a new connection.

, if-connected. , , .

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)
+1

Source: https://habr.com/ru/post/1627843/


All Articles