gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:59:43 25 4
gpt4 key购买 nike

我正在尝试使用套接字在 Python 中制作一个简单的客户端/服务器聊天应用程序,并最终将其变成一个石头剪刀布的网络游戏。

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

客户端.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)

客户端.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)

关于python - 带套接字的简单 Python 聊天应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35276924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com