[英]Python Socket Programming Client "quit not working
I made a simple Chat Server using Python. 我使用Python创建了一个简单的聊天服务器。 I'm having trouble quitting the program from the client side.
我无法从客户端退出程序。 When connected I need to be able to type "/quit" and the program should disconnect from both sides, client and server.
连接后,我需要能够键入“ / quit”,并且程序应与客户端和服务器双方断开连接。 here is my code:
这是我的代码:
alias= raw_input("Name: ")
print 'Connected to remote host. You can start sending messages'
sys.stdout.write(alias + '->'); sys.stdout.flush()
while 1:
socket_list = [sys.stdin, s]
# Get the list sockets which are readable
read_sockets, write_sockets, error_sockets =
select.select(socket_list , [], [])
for sock in read_sockets:
if sock == s:
# incoming message from remote server, s
data = sock.recv(4096)
print data
if not data :
print '\nServer has ended Connection'
sys.exit()
else :
#print data
sys.stdout.write(data)
sys.stdout.write(alias + '->'); sys.stdout.flush()
else :
# user entered a message
msg = alias + '->' + sys.stdin.readline()
quit = '/quit'
#print msg == quit
print
if msg is quit:
print "Goodbye"
s.close()
sys.exit()
else:
s.send(msg)
sys.stdout.write(alias + '->')
sys.stdout.flush()
Your line if msg is quit
should be if msg == quit
. if msg is quit
您的行应该是if msg == quit
。 is
tests for identity, not equality. is
测试身份,而不是平等。 If you were testing if two objects were the same, you would use is
here. 如果要测试两个对象是否相同,
is
在此处使用。 However since you are comparing two strings, you must use ==
. 但是,由于要比较两个字符串,因此必须使用
==
。
Also, your msg
variable is equal to alias + -> + readline
. 另外,您的
msg
变量等于alias + -> + readline
。 therefore "name -> /quit"
will never equal '/quit'
. 因此
"name -> /quit"
永远不会等于'/quit'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.