我正在嘗試通過撰寫一個連接了一個服務器和多個客戶端的簡單聊天程式來學習 python 中套接字的使用。當我只連接一個客戶端時,一切都運行良好,但如果我連接第二個客戶端,第一個客戶端繼續接收訊息,但不能再發送它們。
這是服務器:
from pickle import TRUE
import socket
import threaded
from threading import Thread
import _thread
import os
import time
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)
ip = str(local_ip)
port = 55555
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((ip, port))
server.listen()
global clients
clients = []
def recive(client):
global clients
name = client.recv(2024)
name = name.decode("utf-8")
while True:
try:
string = client.recv(2024)
string = string.decode("utf-8")
if string == "!exit":
client.close()
print("Connection interrupted")
break
else:
for client in clients:
client.send(bytes(string, "utf-8"))
print(f"{name}: {string}")
except:
client.close()
print("Connection interrupted")
break
if __name__ == "__main__":
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)
ip = str(local_ip)
port = 55555
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((ip, port))
server.listen()
print(f"Server listening on {ip} on port {port}")
while True:
client, address = server.accept()
print(f"Connectione estabished - {address[0]}:{address[1]}")
clients.append(client)
_thread.start_new_thread(recive ,(client,))
這是客戶端:
from email import message
import socket
from xml.etree.ElementTree import tostring
import threaded
from threading import Thread
import _thread
import os
import time
global string
global text
string = "string"
text = "text"
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)
ip = str(local_ip)
port = 55555
name = str(input("Insert your name: "))
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.connect((ip, port))
def recive(server):
global string
global text
while True:
text = server.recv(2024)
text = text.decode('utf-8')
if text == string:
pass
else:
print(f"Broadcasted: {text}")
def send(server):
global string
global text
server.send(bytes(name, "utf-8"))
while True:
string = str(input("Enter string: "))
if string == "!exit":
server.send(bytes(string, "utf-8"))
server.close()
break
else:
server.send(bytes(string, "utf-8"))
_thread.start_new_thread(recive ,(server,))
send(server)
如果需要其他資訊,我會注意修改請求并插入它們。
由于英語不是我的第一語言,我為任何錯誤道歉。
uj5u.com熱心網友回復:
在函式def recive(client): ...中,變數client保存用于與特定客戶端通信的套接字。但在這個回圈中:
for client in clients:
client.send(bytes(string, "utf-8"))
print(f"{name}: {string}")
變數被覆寫,在client回圈之后,函式與錯誤的套接字進行通信,即錯誤的客戶端。只需使用一個單獨的變數:
for c in clients:
c.send(bytes(string, "utf-8"))
PS 為防止Address already in use在重新啟動服務器時出現錯誤,請在該行之前添加server.bind(...):
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/492896.html
下一篇:通過JNI系結套接字
