为什么只有if语句中的某些行执行?

时间:2016-07-20 00:24:43

标签: python sockets

import sys
import re
import SocketServer
from sys import stdin
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.

It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""

def handle(self):
    server_msg = "Enter name:\n"
    sent = self.request.send(server_msg);
    self.handle_buffer = self.request.recv(1024).strip()
    server_msg = "That's a nice name\n"
    self.request.send(server_msg);

quit = 0
while quit < 1:
        print "Test Print 2" 

        # self.request is the TCP socket connected to the client
        self.client_response = self.request.recv(500).strip()
        self.handle_buffer.strip()
        self.client_response.strip()

        x = self.handle_buffer.split("\n", 1)
        y = self.client_response.split("\n",1)
        a = x[0]
        b = y[0]
        print a + "> " + b;
        sys.stdout.write(' You> ')
        sys.stdout.flush()
        server_msg = stdin.readline()
        if(server_msg is "\quit"):
            quit = 1;
            print "Test Print 1";
            self.request.send("The client has decided to close this connection. Good day.")
            self.request.close()
            quit = 1
            break;
        else:
            self.request.send(server_msg)
            print "Awaiting response from client..."



if __name__ == "__main__":
    HOST, PORT = "localhost", 9004

    # Create the server, binding to localhost on port 9004
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

if循环if(server_msg is "\quit"):应首先打印&#34;测试打印1&#34;然后将结束消息发送到客户端程序,然后关闭套接字并中断while循环。相反,它没有打印出来&#34;测试打印1&#34;完全没有,但它确实发送了&#34;客户端决定关闭此连接。美好的一天。&#34; 消息(我应该说服务器,而不是客户端)并关闭客户端的套接字,然后继续循环,这些是命令中的结果输入\ quit时的行:

You> \quit
Awaiting response from client...
Test Print 2
client_name>
You>

所以看起来\ quit只会导致if语句中的两行执行,并且由于某种原因,else语句也会运行?这对我没有任何意义。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

您确定服务器收到此字符串 - &#34;客户端已决定关闭此连接。美好的一天。&#34;?

你的if语句的问题是&#34;是&#34;比较,它比较两个变量是否指向同一个对象,而不是它们的值。

按如下方式更换:

if server_msg == "\quit":

有关详细信息,请参阅此问题:Is there a difference between `==` and `is` in Python?