[D]python写的服务器和客户端
根据书上写的服务器段代码:
from socket import *from time import ctimeHOST = ''PORT = 21567BUFSIZ = 1024ADDR = (HOST,PORT)tcpSerSock = socket(AF_INET,SOCK_STREAM)tcpSerSock.bind(ADDR)tcpSerSock.listen(5)while True: print ('Waiting for connection...') tcpCliSock, addr = tcpSerSock.accept() print ('...connected from:',addr) while True: data = tcpCliSock.recv(BUFSIZ) if not data: break tcpCliSock.send('[%s] %s' % (ctime(),data)) tcpCliSock.close()tcpSerSock.close()
from socket import *HOST = 'LOCALHOST'PORT = 21567BUFSIZ = 1024ADDR = (HOST,PORT)tcpCliSock = socket(AF_INET, SOCK_STREAM)tcpCliSock.connect(ADDR)while True: data = input('>') if not data: break tcpCliSock.send(data) data = tcpCliSock.recv(BUFSIZ) if not data: break print(data)tcpCliScok.close()
tcpCliSock.send( data.encode('ascii') )
[解决办法]
你这根本就是照抄网上的代码吗,send只能发送字符串
[解决办法]
嗯,你这个抄的是2版的代码。py3k要用8bits的bytes
socket.recv(bufsize[, flags])
Receive data from the socket. The return value is a bytes object representing the data received. The maximum amount of data to be received at once is specified by bufsize. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero.
socket.send(bytes[, flags])
Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Returns the number of bytes sent. Applications are responsible for checking that all data has been sent; if only some of the data was transmitted, the application needs to attempt delivery of the remaining data. For further information on this topic, consult the Socket Programming HOWTO.
[解决办法]
#Python3.2str(b"ddd","utf-8")bytes("ddd","utf-8")
[解决办法]
更换为了2.7版本的python就可以通过了。你这是3 .2版本的py