我找不到为什么线程在我的代码中不起作用
我试图使用 Python 中的套接字模块制作一个简单的聊天应用程序。在我的 client.py 文件中,我创建了两个函数,一个用于写入,一个用于从服务器接收消息。由于它必须同时运行,所以我使用了线程模块。但它不起作用,我不知道为什么。这是我的代码:
import socket
import threading
SERVER = socket.gethostbyname(socket.gethostname())
PORT = 5050
HEADER = 1024
FORMAT = "utf-8"
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect((SERVER, PORT))
def write():
while True:
message = input()
socket.send(message.encode(FORMAT))
threading.Thread(write())
def receive():
while True:
try:
msg = socket.recv(HEADER).decode(FORMAT)
print(msg)
except:
print('You have been disconnected!')
socket.close()
break
write_thread = threading.Thread(target=write())
recv_thread = threading.Thread(target=receive())
recv_thread.start()
write_thread.start()
I was trying to make a simple chat application using the socket module in Python. In my client.py
file I created two functions, one for writing and one for receiving messages from the server. As it must be run simultaneously, I used the threading module. But it's not working and I don't have a clue why. Here's my code:
import socket
import threading
SERVER = socket.gethostbyname(socket.gethostname())
PORT = 5050
HEADER = 1024
FORMAT = "utf-8"
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect((SERVER, PORT))
def write():
while True:
message = input()
socket.send(message.encode(FORMAT))
threading.Thread(write())
def receive():
while True:
try:
msg = socket.recv(HEADER).decode(FORMAT)
print(msg)
except:
print('You have been disconnected!')
socket.close()
break
write_thread = threading.Thread(target=write())
recv_thread = threading.Thread(target=receive())
recv_thread.start()
write_thread.start()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将来要修复的事情:(
SERVER = "localhost"
错误:
应该是(否则您调用函数而不是将它们作为参数提供):
Things to fix in the future:
SERVER = "localhost"
Error:
Should be(else you call the functions instead of giving them as a parameter):