我找不到为什么线程在我的代码中不起作用

发布于 2025-01-13 16:05:23 字数 877 浏览 0 评论 0原文

我试图使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

久夏青 2025-01-20 16:05:23

将来要修复的事情:(

  1. 第 4 行):我认为您想要做的是 SERVER = "localhost"
  2. (第 15 行):这是未使用的

错误:

write_thread = threading.Thread(target=write())
recv_thread = threading.Thread(target=receive())

应该是(否则您调用函数而不是将它们作为参数提供):

write_thread = threading.Thread(target=write)
recv_thread = threading.Thread(target=receive)

Things to fix in the future:

  1. (Line 4): I think what you want to do is SERVER = "localhost"
  2. (Line 15): This is unused

Error:

write_thread = threading.Thread(target=write())
recv_thread = threading.Thread(target=receive())

Should be(else you call the functions instead of giving them as a parameter):

write_thread = threading.Thread(target=write)
recv_thread = threading.Thread(target=receive)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文