安妮妮妮知道我如何解决此问题吗?还是annyone在我的代码中看到错误?
因此,我正在尝试设置基本的localhost套接字服务器。这样我就可以在计算机和树莓派之间发送数据。我现在只想要一个基本的聊天程序,以便以后可以尝试向服务器中添加更多代码,以便它对某些消息做出响应。
我有一个基本的服务器和一个客户端,它们可以相互连接,但是客户端无法发送消息。而且,当我连接另一个客户端时,我无法发送消息,也不知道为什么。
2天前,我几乎使用了相同的代码(很愚蠢,没有保存最后一部分,现在全部消失了……),但是我遇到了第二个客户端无法发送消息的问题。 / p>
(顺便说一句,您知道,我是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"))
答案 0 :(得分:0)
我更改了您的服务器代码:
它现在可用于多个客户,我让您看看:
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