我正在尝试设置一个消息传递应用程序,这很有趣,但是服务器没有将我的消息回显给客户端。
我有2个文件,为了方便使用,我计划将它们合并为1个,这些文件是client.py和server.py。
我的应用程序正常工作,但是随后另一个用户说我的server.py只能处理1个连接,因此我打算将其设置为理论上无限的程序(减去硬件限制等)
client.py看起来像...
## -- Setup -- ##
## Lib
from socket import *
import socket
## Vars
host = input("Host: ") # Host/IP of the server
port = int(input("Port: ")) # Int of the port that the server is listening on
username = input("Username: ")
username = "<" + username + ">"
print(f"Connecting under nick \"{username}\"")
## -- Main -- ##
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Creates socket
clientsocket.connect((host, port)) # Connects to the server
while True: # Sending message loop
Csend = input("MSG: ") # Input message
#Csend = f"{username} {Csend}" # Add username to message
clientsocket.send(Csend.encode()) # Send message to ONLY the server
print(clientsocket.recv(1024).decode())
这用于连接到服务器,我担心while循环,因为它们可能会干扰我的Tkinter GUI(稍后再进行设置)。
server.py看起来像...
## -- Setup -- ##
## Lib
import socket # Import socket module
try:
import thread
except:
import threading
## Server
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host_name = socket.gethostname() # Get Name
host = socket.gethostbyname(host_name) # Get IP
port = int(input("What port are you listening on?\n"))
print(f"Server started!\nHost: {host}\nPort: {port}")
print("Waiting for clients...")
serversocket.bind((host, port)) # Bind to the port
serversocket.listen(5) # Now wait for client connection.
## -- Subprograms -- ##
def new_client(clientsocket, address):
print(f"{address} connected")
while True:
Srecv = clientsocket.recv(1024).decode()
print(f"{address}: \"{msg}\"")
# CHECKS AND GAMES GO HERE - (game plugins using txt for import dir?)
clientsocket.sendall(Srecv.encode())
clientsocket.close()
## -- Main -- ##
while True:
clientsocket, address = serversocket.accept() # Accept incoming connections
threading.Thread(target = new_client, args = (clientsocket,address))
serversocket.close()
用户建议我使用线程使服务器准备好进行多客户端连接。
目标我们的目标是要有一个可以跨连接工作的消息传递应用程序,现在我正在同一台计算机(有时是本地主机)上对其进行测试,但是我希望能够向在不同连接上使用不同操作系统的朋友发送消息。
想法是,发送消息时,它使用sendall将其回显给原始发送者,并将消息传递到每个连接。
因此,如果我的代码在理论上按预期工作,则对客户端的预期输出将是
<MSG> hello
hello
对于服务器,它将是...
[person address]: hello
如果要创建类似聊天服务器的内容,则需要跟踪所有已连接的客户端。不要被socket.sendall()
方法所迷惑,它只是将所有字节发送到给定的套接字,与将数据发送到您可能想到的所有套接字无关。
我试图稍微调整一下代码以显示出大致的想法,但我尚未对其进行测试:
请不要将客户端和服务器合并到同一文件中。最好在编程时分解事物,而不是将事物合并在一起。## -- Subprograms -- ## def new_client(clientsocket, address): print(f"{address} connected") while True: Srecv = clientsocket.recv(1024).decode() print(f"{address}: \"{msg}\"") # CHECKS AND GAMES GO HERE - (game plugins using txt for import dir?) # Don't forget error handling! for sock in clients.values(): sock.sendall(Srecv.encode()) clientsocket.close() del clients[address] clients = {} ## -- Main -- ## while True: clientsocket, address = serversocket.accept() # Accept incoming connections clients[address] = clientsocket threading.Thread(target = new_client, args = (clientsocket,address)) serversocket.close()
P.S。