【发布时间】:2021-12-03 15:47:29
【问题描述】:
客户端能够成功连接到服务器,但是当我从一个客户端发送消息“!sendall”时,列表中的其他客户端没有收到此消息“发送给所有人!”。我不确定我做错了什么。请协助。谢谢。
server.py
import socket
import os
from _thread import *
ServerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ServerSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
host = '192.168.3.248'
port = 9368
ThreadCount = 0
ipList = []
conList = []
try:
ServerSocket.bind((host, port))
except socket.error as e:
print(str(e))
print('Waiting for a Connection..')
ServerSocket.listen(5)
def threaded_client(connection, addr):
connection.send(str.encode('Welcome to the Server'))
while True:
data = connection.recv(2048)
print(data.decode())
if data.decode()[0:2] == '!q':
connection.close()
break;
elif data.decode()[0:8] == '!sendall':
for ipAddr in ipList:
if addr != ipAddr:
connection.sendto(b'Sending this to All!', ipAddr)
else:
reply = 'Server Says: ' + data.decode('utf-8')
connection.sendall(str.encode(reply))
if not data:
break
connection.close()
while True:
Client, address = ServerSocket.accept()
if address not in ipList:
ipList.append(address)
if Client not in conList:
conList.append(Client)
print('Connected to: ' + address[0] + ':' + str(address[1]))
print("Added IP to the list")
start_new_thread(threaded_client, (Client, address, ))
ThreadCount += 1
print('Thread Number: ' + str(ThreadCount))
ServerSocket.close()
client.py
import socket
ClientSocket = socket.socket()
host = '192.168.3.248'
port = 9368
print('Waiting for connection')
try:
ClientSocket.connect((host, port))
except socket.error as e:
print(str(e))
Response = ClientSocket.recv(1024)
while True:
Input = input('Say Something: ')
ClientSocket.send(str.encode(Input))
Response = ClientSocket.recv(1024)
print(Response.decode('utf-8'))
ClientSocket.close()
----从服务器输出----
Waiting for a Connection..
Connected to: 192.168.3.114:49968
Added IP to the list
Thread Number: 1
Connected to: 192.168.3.248:30750
Added IP to the list
Thread Number: 2
---- 来自一个客户端的输出 -----
Waiting for connection
Say Something: Hello
Server Says: Hello
Say Something: !sendall
Sending this to All! <---------- The other connected clients doesn't receive this message, which they are supposed to receieve
【问题讨论】:
标签: python-3.x sockets client-server