控制socketserver中的传入字

时间:2014-06-05 10:53:56

标签: python python-2.7 socketserver

这是我在python中的程序

#!usr/bin/python
import SocketServer

class Echohandler(SocketServer.BaseRequestHandler):
    def handle(self):
        print "Got Connection form :",self.client_address
        while True:
            data = self.request.recv(1024)
            if data == "hi":
                self.request.send("HI there!")

serveradder = ("0.0.0.0",9002)
SocketServer.TCPServer.allow_reuse_address = True
server = SocketServer.TCPServer(serveradder,Echohandler)
server.serve_forever()

当我连接到服务器并发送hi服务器时,只需返回hi而不发送HI! 我该如何解决这个问题?!

2 个答案:

答案 0 :(得分:0)

答案是self.data!

#!usr/bin/python
import SocketServer

class Echohandler(SocketServer.BaseRequestHandler):
    def handle(self):
        print "Got Connection form :",self.client_address
        while True:
            data = ''
            self.data = self.request.recv(1024)
            data = self.data
            #self.request.send(data)
            if str(data).strip() == 'hi' :
                self.request.send("HI there!")

serveradder = ("127.0.0.1",9002)
SocketServer.TCPServer.allow_reuse_address = True
server = SocketServer.TCPServer(serveradder,Echohandler)
server.serve_forever()

答案 1 :(得分:-2)

你必须先删除数据!

#!usr/bin/python
import SocketServer

class Echohandler(SocketServer.BaseRequestHandler):
    def handle(self):
        print "Got Connection form :",self.client_address
        while True:
            data = self.request.recv(1024)
            if str(data).strip() == "hi":
                self.request.send("HI there!")

serveradder = ("0.0.0.0",9002)
SocketServer.TCPServer.allow_reuse_address = True
server = SocketServer.TCPServer(serveradder,Echohandler)
server.serve_forever()`