python创建tcp服务端和客户端
程序员文章站
2022-03-12 18:23:30
1.tcp服务端server 2.tcp客户端client ......
1.tcp服务端server
1 from socket import * 2 from time import ctime 3 4 host = '' 5 port = 9999 6 bufsiz = 1024 7 addr = (host, port) 8 9 tcpsersock = socket(af_inet, sock_stream) #创建套接字 10 tcpsersock.bind(addr) #绑定ip和端口 11 tcpsersock.listen(5) #监听端口,最多5人排队 12 13 while true: 14 print('waiting for connection...') 15 tcpclisock, addr = tcpsersock.accept() #建立连接 16 print('...connected from:', addr) 17 18 while true: 19 data = tcpclisock.recv(bufsiz) 20 if not data: 21 break 22 content = '[%s] %s' % (bytes(ctime(), "utf-8"), data) 23 print(data) 24 print(type(content)) 25 tcpclisock.send(content.encode("utf-8")) 26 27 tcpclisock.close() 28 29 tcpsersock.close()
2.tcp客户端client
1 from socket import * 2 3 host = '127.0.0.1' # or 'localhost' 4 port = 9999 5 bufsiz = 1024 6 addr = (host, port) 7 8 tcpclisock = socket(af_inet, sock_stream) 9 tcpclisock.connect(addr) 10 11 while true: 12 data = input('> ') 13 if not data: 14 break 15 16 tcpclisock.send(data.encode("utf-8")) 17 data = tcpclisock.recv(bufsiz) 18 if not data: 19 break 20 print(data.decode("utf-8")) 21 22 tcpclisock.close()
上一篇: 课时47:魔法方法:定制序列
下一篇: Python_实用入门篇_12