0
首先作爲一個免責聲明:我不是Python中最偉大的(或一般編程)。Python套接字 - 多個客戶
話雖如此,我遇到了Python套接字的問題。我試圖構建一個簡單的聊天客戶端/服務器程序,但是,我無法讓服務器將從一個客戶端套接字接收到的相應消息發送給其他連接的客戶端。
這裏是服務器代碼:
#!/usr/bin/python
import socket
import fnmatch
import thread
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
## Allow socket to be reused by application - doesn't force timeout.
serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
host = socket.gethostname()
port = 9000
serverSocket.bind((host,port))
connectedUsers = []
serverSocket.listen(5)
def threadedClient(clientStream):
while True:
clientMessage = clientStream.recv(1024).decode()
print clientMessage
if "Username:" in clientMessage:
username = clientMessage.replace("Username:","")
print str(username) + " has connected!"
connectedUsers.append(clientAddress)
print str(username) + "" + str(clientAddress) + " has connected to server"
for users in connectedUsers:
clientStream.sendto(str(username) + " has connected!", users)
if "Text:" in clientMessage:
receievedText = clientMessage.replace("Text:","")
for users in connectedUsers:
clientStream.sendto(receievedText.encode(), users)
print "Sending message " + str(receievedText) +" to:" + str(users)
if not clientMessage:
break
while True:
clientStream, clientAddress = serverSocket.accept()
thread.start_new_thread(threadedClient,(clientStream,))
這裏是客戶端代碼:
#!/usr/bin/python
import socket
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 9000
username = raw_input("Please enter username: ")
clientSocket.connect((host, port))
clientSocket.send("Username:" + username)
def receiveServerMessage():
serverMessage = clientSocket.recv(1024).decode()
print serverMessage + '\n'
while True:
receiveServerMessage()
command = raw_input(username + " > ")
if command != None:
clientSocket.send("Text:" + str.encode(command))
if command == str("q"):
exit()
clientSocket.close()
迭代似乎試圖將消息發送到其他連接的客戶端時要出差錯。我不確定「sendto」是否是處理這種情況的正確方法......特別是因爲我相信它是基於UDP的。有關如何正確處理套接字流的任何建議?
我建議你開始使用TCP而不是UDP,因爲它是一種更簡單的方法。 – lilezek
@lilezek看起來像tcp socket.socket(socket.AF_INET,socket.SOCK_STREAM) – WalterM
我相信命令「sendto」與udp有某種關係的唯一原因是,大多數教程/文檔找到在線是專門針對UDP的。但是,機器上的tcpdump僅顯示TCP通信。 – icehac