server.py
import socket
import threading
client_ip = {
"h1": "10.0.0.1",
"h2": "10.0.0.2",
"h3": "10.0.0.3",
}
client_host = {
"10.0.0.1" : "h1",
"10.0.0.2" : "h2",
"10.0.0.3" : "h3",
}
port = 14514
def handle_connection(conn, addr):
print(f"connection from {addr} has been established.")
host = client_host[addr[0]]
while True:
try:
message = conn.recv(1024).decode()
if not message:
break
target, msg = message.split(':', 1)
if target.find("To ") != 0:
raise Exception("Invalid dest")
target = target[3:]
target_ip = client_ip.get(target.strip())
if target_ip:
forward_message(host, target_ip, msg.strip())
else:
raise Exception(f"Unknown target: {target}")
except Exception as e:
print(f"Error: {e}")
break
conn.close()
print(f"{addr} closed.")
def forward_message(host, target_ip, message):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as forward_socket:
try:
forward_socket.connect((target_ip, port))
forward_socket.send((message + f" From {host}").encode())
print(f"Forwarded message to {target_ip}: {message}")
except Exception as e:
print(f"failed to forward message to {target_ip}: {e}")
def start_server():
host = ""
server_socket = socket.socket()
server_socket.bind((host, port))
server_socket.listen(10)
print("Server h4 started")
while True:
conn, addr = server_socket.accept()
client_handler = threading.Thread(target = handle_connection, args = (conn, addr))
client_handler.start()
def main():
start_server()
if __name__ == '__main__':
main()
topology.py
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.util import dumpNodeConnections
from mininet.log import setLogLevel
from mininet.cli import CLI
class ChatRoomTopo(Topo):
def build(self):
s1 = self.addSwitch("s1")
s2 = self.addSwitch("s2")
s3 = self.addSwitch("s3")
h1 = self.addHost("h1")
h2 = self.addHost("h2")
h3 = self.addHost("h3")
h4 = self.addHost("h4")
self.addLink(h1, s3)
self.addLink(h2, s1)
self.addLink(h3, s3)
self.addLink(h4, s2)
self.addLink(s1, s2)
self.addLink(s1, s3)
def simpleTest():
"Create and test a simple network"
topo = ChatRoomTopo()
net = Mininet(topo)
net.start()
CLI(net)
net.stop()
if __name__ == '__main__':
setLogLevel('info')
simpleTest()
user.py
import socket
import threading
def handle_send(client_send_socket):
while True:
message = input("Enter message: ")
if message.lower() == 'exit':
break
client_send_socket.send(message.encode())
def handle_recv(client_recv_socket):
while True:
conn, addr = client_recv_socket.accept()
try:
message = conn.recv(1024).decode()
if not message:
break
print ("\n" + message)
except Exception as e:
print(f"Error: {e}")
break
conn.close()
def start_client():
h4_ip = "10.0.0.4"
host = h4_ip
port = 14514
client_send_socket = socket.socket() # default is TCP
client_send_socket.connect((host, port))
client_recv_socket = socket.socket()
client_recv_socket.bind(("", port))
client_recv_socket.listen(10)
client_send_handler = threading.Thread(target = handle_send, args = (client_send_socket,))
client_recv_handler = threading.Thread(target = handle_recv, args = (client_recv_socket,))
client_recv_handler.start()
client_send_handler.start()
def main():
start_client()
if __name__ == '__main__':
main()
udpclient.py
import socket
import threading
import subprocess
client_ip = {
"h1": "10.0.0.1",
"h2": "10.0.0.2",
"h3": "10.0.0.3",
"h4": "10.0.0.4",
}
client_host = {
"10.0.0.1" : "h1",
"10.0.0.2" : "h2",
"10.0.0.3" : "h3",
"10.0.0.4" : "h4",
}
port = 14514
OUTPUT_ALL = False
def get_local_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("10.0.0.1", 80))
ip_address = s.getsockname()[0]
except Exception as e:
ip_address = '127.0.0.1'
finally:
s.close()
return ip_address
def handle_send(client_send_socket):
host = client_host.get(get_local_ip())
while True:
message = input("Enter message: ")
try:
if message.lower() == 'exit':
break
target, msg = message.split(':', 1)
if target.find("To ") != 0:
raise Exception("Invalid dest")
target = target[3:]
target_ip = client_ip.get(target.strip())
if target_ip:
client_send_socket.sendto((msg + f" From {host}").strip().encode(), (target_ip, port))
else:
raise Exception(f"Unknown target: {target}")
except Exception as e:
print(f"Error: {e}")
def handle_recv(client_recv_socket):
client_recv_socket.bind(("", port))
while True:
message, client_addr = client_recv_socket.recvfrom(1024)
if OUTPUT_ALL or (client_addr[0] != get_local_ip()):
print ("\n" + message.decode())
def start_udpclient():
client_send_socket = socket.socket(family = socket.AF_INET, type = socket.SOCK_DGRAM)
client_recv_socket = socket.socket(family = socket.AF_INET, type = socket.SOCK_DGRAM)
client_send_handler = threading.Thread(target = handle_send, args = (client_send_socket,))
client_recv_handler = threading.Thread(target = handle_recv, args = (client_recv_socket,))
print (f"Client {get_local_ip()} begins to work")
client_recv_handler.start()
client_send_handler.start()
def main():
start_udpclient()
if __name__ == '__main__':
main()
标签:socket,猫猫,ip,client,喜欢,message,recv,target
From: https://www.cnblogs.com/qixingzhi/p/18608671