首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

[D]python写的服务器和客户端,该如何解决

2012-06-15 
[D]python写的服务器和客户端根据书上写的服务器段代码:Python codefrom socket import *from time import

[D]python写的服务器和客户端
根据书上写的服务器段代码:

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

客户端代码:
Python code
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()

运行时客户端出错
输入hi,然后回车,出现下列错误代码,
Traceback (most recent call last):
  File "F:\Python Work\tsTclnt.py", line 15, in <module>
  tcpCliSock.send(data)
TypeError: 'str' does not support the buffer interface


--------------------------
Double行动:
原帖分数:40
加分:40

[解决办法]
试试:
Python code
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.


[解决办法]
Python code
#Python3.2str(b"ddd","utf-8")bytes("ddd","utf-8")
[解决办法]
更换为了2.7版本的python就可以通过了。你这是3 .2版本的py

热点排行