Python之路——网络编程,,socketTCP服


socket

TCP

服务端

 1 import socket 2 sk = socket.socket() 3 sk.bind((‘127.0.0.1‘,8080)) # 绑定ip和端口号 4 sk.listen() # Enable a server to accept connections. 5 conn,addr = sk.accept() # Wait for an incoming connection.  Return a new socket 6                         # representing the connection, and the address of the client. 7 while 1: 8     content = conn.recv(1024)   # 接收 9     print(content.decode(‘utf-8‘))10     conn.send(content+b‘--liuyankui‘)   # 发送11 conn.close()12 sk.close()

客户端

1 import socket2 sk = socket.socket()3 sk.connect((‘127.0.0.1‘,8080))  #连接4 while 1:5     content = input(‘>>>‘).encode(‘utf-8‘)6     sk.send(content)7     ret = sk.recv(1024)8     print(ret.decode(‘utf-8‘))9 sk.close()

UDP

服务端

1 import socket2 sk = socket.socket(type=socket.SOCK_DGRAM)3 sk.bind((‘127.0.0.1‘,8080))4 msg ,addr = sk.recvfrom(1024)5 print(msg.decode(‘utf-8‘))6 sk.sendto(b‘bye‘,addr)7 sk.close()

用户端

1 import socket2 sk = socket.socket(type=socket.SOCK_DGRAM)3 ip_port = (‘127.0.0.1‘,8080)4 sk.sendto(b‘hello‘,ip_port)5 msg,addr = sk.recvfrom(1024)6 print(msg.decode(‘utf-8‘))7 sk.close()

Python之路——网络编程

评论关闭