繁体   English   中英

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

[英]Simple Python chat app with 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)             

有帮助吗? 谢谢。

就像@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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM