带套接字的简单Python聊天应用程序

时间:2016-02-08 18:41:44

标签: python sockets

我正在尝试使用套接字在Python中创建一个简单的客户端/服务器聊天应用程序,并最终将其转换为Rock,Paper,Scissors的联网游戏。

我在网上找到了一个创建客户端/服务器的指南但是我在修改循环时遇到了问题,因此每个脚本都会侦听另一个脚本,收到一条消息,然后显示一条raw_input,它成为发送到另一个脚本的消息,等等。这是代码:

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)             

有任何帮助吗?谢谢。

1 个答案:

答案 0 :(得分:3)

就像@DavidCullen在评论中所说,你是第二次通过while循环停止服务器接受新连接。

您可以通过执行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)