服务端程序
// TCPServer.py import socket hostName = '127.0.0.1' port = 9000 address = (hostName, port) # 开放的地址和端口 # 1.创建socket对象,采用ipv4协议、流式数据传输(面向连接) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(address) # 2.绑定地址与端口 server.listen(5) # 3.设置监听数 print(address, ' ESTABLISHED') s, addr = server.accept() # 4.等待客户端的连接 print(addr, " CONNECTED") while True: content = s.recv(1024) # 5.接收来自客户端的数据 if content.decode() == 'EXIT': s.close() # 7.关闭连接 print(addr, " DISCONNECT") break print(addr, ':', content.decode()) # 6.发送数据给客户端 s.send(bytes(content.decode()+" SUCCESS RECEIVED", encoding='utf-8')) print("SERVER TERMINATE") server.close() # 8.服务端关闭
客户端程序
// TCPClient.py import socket hostName = '127.0.0.1' port = 9000 address = (hostName, port) # 服务端的地址和端口 # 1.创建socket对象,采用ipv4协议、流式数据传输(面向连接) client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(address) # 2.连接服务器 print("SERVER ConNECT SUCCESS") print("INPUT 'EXIT' TO TERMINATE") while True: content = input(">>>") if(content == 'EXIT'): client.send(bytes(content, encoding='utf-8')) client.close() break client.send(bytes(content, encoding='utf-8')) content = client.recv(1024) print("SERVER RESPONSE:", content.decode())UDP 客户-服务器程序
服务端程序
// UDPServer.py import socket hostName = '127.0.0.1' port = 9000 address = (hostName, port) # 1.使用数据报式传输(面向无连接) server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server.bind(address) # 2.绑定地址与端口 print("ESTABLISH ", address) while True: content, addr = server.recvfrom(1024) # 3.接收数据,使用recvfrom print(addr, ":", content.decode()) # 4.使用sendto发送数据 server.sendto( bytes(content.decode()+" SUCCESS RECEIVED", encoding='utf-8'), addr)
客户端程序
// UDPClient.py import socket hostName = '127.0.0.1' port = 9000 address = (hostName, port) client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) print("INPUT 'EXIT' TO TERMINATE") while True: content = input('>>> ') if content == 'EXIT': client.close() break client.sendto(bytes(content, encoding='utf-8'), address) content, addr = client.recvfrom(1024) print("SERVER RESPONSE:", content.decode('utf-8'))
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)