1.UDP,我这里暂时没写代码,懒得写了,
2.TCP:
2.1TCP服务端
import socket from multiprocessing import Process # 开两个进程,然后一个接收,一个发送 def receive(con): while True: recv_cmd = con.recv(1024) print(recv_cmd.decode("utf-8")) def send(con): while True: msg = input("") con.send(f"{' '*20}friend:{msg}\n".encode("utf-8")) if __name__ == "__main__": phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM) phone.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) phone.bind(("127.0.0.1", 8080)) # 0-1024给操作系统用 --65535 phone.listen(5) # 等待链接 con, b = phone.accept() print("The connection is complete. You can chat") p_receive = Process(target=receive, args=(con,)) p_receive.start() send(con)View Code
2.2TCP客户端
import socket from multiprocessing import Process # 开两个进程,然后一个接收,一个发送 def receive(phone): while True: recv_cmd = phone.recv(1024) print(recv_cmd.decode("utf-8")) def send(phone): while True: msg = input("") phone.send(f"{' '*30}friend:{msg}\n".encode("utf-8")) if __name__ == "__main__": phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM) phone.connect(("127.0.0.1", 8080)) print("The connection is complete. You can chat") p_receive = Process(target=receive, args=(phone,)) p_receive.start() send(phone)View Code
3两者区别:
TCP:实时连接,安全性高
UDP:不连接直接发送,管你能不能收到呢