gpt4 book ai didi

python - python多个客户端聊天不起作用

转载 作者:行者123 更新时间:2023-12-03 11:58:43 26 4
gpt4 key购买 nike

当我运行main和client的py文件时,未显示错误,但未显示发送消息的输入。怎么修?
main.py结果->等待中...并已连接192.168.1.26 58767
client.py结果->没有
这是main.py

import threading
import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

host="192.168.1.26"
port=1111
threadcount=0
server.bind((host,port))
print("Waiting...")
server.listen(3)


def clients(connection):
connection.send(str.encode("welcome\n"))
while True:
data=connection.recv(2048)
reply="server says" + data.decode("utf-8")
if not data:
break
connection.sendall(str.encode(reply))
connection.close()

while True:
client,adress=server.accept()
print("connected"+ str(adress[0]) + " " + str(adress[1]))
threading.Thread(target=clients,args=(client,))
threadcount+=1
server.close()
这是clients.py
import socket

client_socket=socket.socket()
host="192.168.1.26"
port=1111
client_socket.connect((host,port))

response=client_socket.recv(1024)
print("hello")

while True:
input=input("say")
client_socket.send(str.encode(input))
Response=client_socket.recv(1024)
print(Response.decode("utf-8"))

client_socket.close()

最佳答案

看来您的线程从未真正启动过。一种解决方案是定义一个在run例程中实现线程逻辑的类。该类应继承threading.Thread。然后,您可以简单地将类初始化为对象并调用其start例程。请尝试以下原始服务器代码的变体。

import threading
import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

host="192.168.1.26"
port=1111
threadcount=0
server.bind((host,port))
print("Waiting...")
server.listen(3)

class ServerThread(threading.Thread):
def __init__(self, threadsocket):
threading.Thread.__init__(self)
self.threadsocket = threadsocket

def run(self):
self.threadsocket.send(str.encode("welcome\n"))
while True:
data=self.threadsocket.recv(2048)
reply="server says" + data.decode("utf-8")
print(reply)
if not data:
break
self.threadsocket.sendall(str.encode(reply))
self.threadsocket.close()

while True:
client,adress=server.accept()
print("connected"+ str(adress[0]) + " " + str(adress[1]))
thread = ServerThread(client)
thread.start()
threadcount+=1

server.close()
就客户端而言,正如我在评论中提到的那样,您不应将 input用作变量名称来存储 input函数的结果。改为将其更改为 data

关于python - python多个客户端聊天不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63675539/

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