python创建tcp服务端和客户端

2018-08-26 17:33:09来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

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()

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:三元表达式、列表推导式、生成器表达式

下一篇:python创建udp服务端和客户端