python的socket程序,哪里出错了?

hello_money 2015-05-16 11:30:07
是书上的代码,win7。每当在客户端输入内容时,服务器端的程序就提示:
File "C:\Python27\lib\socket.py", line 170, in _dummy raise error(EBADF, 'Bad file descriptor') socket.error: [Errno 9] Bad file descriptor
到底是哪里出错了呢?我是初学者,请说得详细些,谢谢。
服务器源程序:
from socket import *
from time import ctime
HOST='127.0.0.1'
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='127.0.0.1'
PORT=21567
BUFSIZ=1024
ADDR=(HOST,PORT)

tcpCliSock=socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)

while True:
data=raw_input('>')
if not data:
break
tcpCliSock.send(data)
data=tcpCliSock.recv(BUFSIZ)
if not data:
break
print data

tcpCliSock.close()
...全文
153 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
panghuhu250 2015-05-19
  • 打赏
  • 举报
回复
tcpCliSock.close() 应该在循环的外面,(和while对齐). 否则, 第一次循环后tcpCliSock就关闭了, 后来再recv就有错了.

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

37,719

社区成员

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

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