170925_1 Python socket 创建TCP的服务器端和客户端

【Python版本】3.6

【遇到的问题】

客户端和服务器端都遇到:TypeError: a bytes-like object is required, not 'str'

【解决方案】

参考:https://stackoverflow.com/questions/13274553/python-3-3-socket-typeerror

 

创建TCP服务器端:

 1 from socket import *
 2 from time import ctime
 3 
 4 host = ''
 5 port = 21563
 6 buf_size = 1024
 7 addr = (host, port)
 8 
 9 
10 tcpSerSock = socket(AF_INET, SOCK_STREAM)
11 tcpSerSock.bind(addr)
12 tcpSerSock.listen(5)
13 
14 while True:
15     print("waiting for connection....")
16     tcpCliSock, ADDR = tcpSerSock.accept()
17     print("...connected from:", ADDR)
18 
19     while True:
20         data = tcpCliSock.recv(buf_size)
21         print(data)
22         print(bytes(ctime(), 'utf-8'))
23         if not data:
24             break
25         response = '[%s] %s' % (ctime(), data.decode('utf-8'))
26         tcpCliSock.send(response.encode('utf-8'))
27     tcpCliSock.close()
28 
29 tcpSerSock.close()

创建TCP客户端:

 1 from socket import *
 2 
 3 
 4 host = 'localhost'
 5 port = 21563
 6 buf_size = 1024
 7 addr = (host, port)
 8 
 9 tcpCliSock = socket(AF_INET, SOCK_STREAM)
10 tcpCliSock.connect(addr)
11 
12 while True:
13     data = input('>')
14 
15     if not data:
16         break
17     tcpCliSock.send(data.encode('utf-8'))
18     data = tcpCliSock.recv(buf_size)
19     if not data:
20         break
21     print(data.decode())
22 
23 tcpCliSock.close()

 

posted @ 2017-09-25 14:38  打不过小怪兽leer  阅读(154)  评论(0编辑  收藏  举报