Python 多线程套接字服务器无法接收来自 2 个用户的消息

Python Multithread socket server can't receive msg from 2 users

有人知道我如何解决这个问题吗?或者有人看到我的代码有错误吗?

所以我正在尝试设置一个基本的本地主机套接字服务器。所以我可以在我的电脑和 raspberry pi 之间发送数据。我现在只想要一个基本的聊天程序,这样我以后可以尝试向我的服务器添加更多代码,以便它响应某些消息。

我有一个基本的服务器和一个客户端,它们可以相互连接,但客户端不能发送消息。而且当我连接另一个客户端时,我无法发送消息,我不知道为什么。

2 天前,我有几乎相同的代码(很愚蠢,没有保存最后一部分,现在全部消失了......)但后来我遇到了第二个客户端无法发送消息的问题.

( 顺便说一下,我对 python 和编程还很陌生,但我想开始学习。所以我的代码可能充满了奇怪的问题,等等。我也有一些不必要的变量,但完成后我会清理这个烂摊子)

谁能帮帮我?

我的代码(完整代码):

import threading
import time
import socket
import sys

NUMBER_OF_THREADS = 2
JOB_NUMBER = [1, 2]
thread_list = []

all_connections = []
all_addresses = []

ip = "localhost"
port = 6969
number_of_connections = 5

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


def receive_msg():
    while True:
        msg = clientsocket.recv(1024)
        print(msg.decode("utf-8"))


def accept_connections():
    while True:
        time.sleep(1)
        s.listen()
        clientsocket, address = s.accept()
        print(f"[Server] New connection with {address}")




# MAIN CODE BEGINNING

t1 = threading.Thread(target = receive_msg, name = "thread_recv_msg", args=())
#t2 = threading.Thread(target = accept_connections, name = "accept_connections", args=())




s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((ip, port))
print("[Server] Server online...")
s.listen(number_of_connections)

while True:
    clientsocket, address = s.accept()
    print(f"[Server] New connection with {address}")

#create_socket()
time.sleep(1)
t1.start()
#t2.start()

# MAIN CODE END

我的客户代码:

import socket
import sys
import time

#####################

Connecting = True

while Connecting == True:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(("localhost", 6969))
    Connecting = False

if Connecting == False:
    print("Verbonden met server!") # dutch for: connected with server!

    while True: 
        msg = input("New message: ")
        time.sleep(1)
        s.sendall(bytes(msg, "utf-8"))

我更改了您的服务器代码:

  • 接受新连接的主循环
  • 每个客户端一个新线程来接收消息

它现在适用于多个客户端,我让你看看:

import threading
import time
import socket
import sys

NUMBER_OF_THREADS = 2
JOB_NUMBER = [1, 2]
thread_list = []

all_connections = []
all_addresses = []

ip = "localhost"
port = 6969
number_of_connections = 5

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((ip, port))
print("[Server] Server online...")
s.listen(number_of_connections)


def receive_msg(clientsocket):
    while True:
        msg = clientsocket.recv(1024).decode("utf-8")
        print(msg)

while True:
    clientsocket, address = s.accept()
    print(f"[Server] New connection with {address}")
    t2 = threading.Thread(target=receive_msg, args=(clientsocket,))
    t2.daemon = True
    t2.start()


# MAIN CODE END