[D]python写的服务器和客户端

自然兰亭 2012-05-08 02:49:01
根据书上写的服务器段代码:

from socket import *
from time import ctime

HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (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 = 21567
BUFSIZ = 1024
ADDR = (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
...全文
534 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
Barton 2012-05-09
  • 打赏
  • 举报
回复

#Python3.2
str(b"ddd","utf-8")
bytes("ddd","utf-8")
自然兰亭 2012-05-09
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

试试:
Python code
tcpCliSock.send( data.encode('ascii') )
[/Quote]这个还是不怎么行
自然兰亭 2012-05-09
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]

你这根本就是照抄网上的代码吗,send只能发送字符串
[/Quote]
这个是书上的代码,我输入后,怎么做才能是字符串呢?
自然兰亭 2012-05-09
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 的回复:]

更换为了2.7版本的python就可以通过了。你这是3 .2版本的py
[/Quote]
我再找找问题吧。
bullswu 2012-05-09
  • 打赏
  • 举报
回复
更换为了2.7版本的python就可以通过了。你这是3 .2版本的py
angel_su 2012-05-08
  • 打赏
  • 举报
回复
嗯,你这个抄的是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.

long552900806 2012-05-08
  • 打赏
  • 举报
回复
你这根本就是照抄网上的代码吗,send只能发送字符串
bugs2k 2012-05-08
  • 打赏
  • 举报
回复
试试:
tcpCliSock.send( data.encode('ascii') )

37,722

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧