import socket
import threading
from multiprocessing import Process
# 定义一个处理客户端连接的函数
def handle_client_connection(client_socket):
try:
while True:
data = client_socket.recv(1024)
if not data:
break
client_socket.sendall(data)
finally:
client_socket.close()
# 定义一个处理监听和接受连接的函数
def server_process(host, port):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(5)
print(f"Server is listening on {host}:{port}")
try:
while True:
client_socket, addr = server_socket.accept()
print(f"Accepted connection from {addr}")
client_handler = threading.Thread(target=handle_client_connection, args=(client_socket,))
client_handler.start()
finally:
server_socket.close()
if __name__ == "__main__":
HOST = '127.0.0.1'
PORT = 12345
NUM_PROCESSES = 4 # 定义服务器进程的数量
# 创建多个进程来运行服务器
processes = []
for _ in range(NUM_PROCESSES):
p = Process(target=server_process, args=(HOST, PORT))
p.start()
processes.append(p)
# 等待所有进程完成
for p in processes:
p.join()
import socket
import struct
def broadcast_message(message, host='<broadcast>', port=12345):
# 创建一个UDP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 允许地址重用
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
# 发送消息
sock.sendto(message.encode(), (host, port))
print("Message broadcasted:", message)
# 关闭套接字
sock.close()
if __name__ == "__main__":
message = "Hello, network!"
broadcast_message(message)