我正在研究用socket和线程构建聊天的python。问题是当我执行或输入“/ quit”时我的客户端不正确存在。程序结束,但提示没有回来。我想我的线程还在运行。 我做错了什么?
# -*- coding: UTF-8 -*-
import socket
from threading import Thread
class Client(Thread):
def __init__(self, server_host, server_port):
Thread.__init__(self)
self.server_host = server_host
self.server_port = server_port
def run(self):
self.connect()
self.accepting = True
self.rec_message()
def connect(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((self.server_host, self.server_port))
print 'Conectado ao servidor %s:%s' % (self.server_host, self.server_port)
def close(self):
print 'Fechar'
self.sock.close()
self.accepting = False
def send_message(self, msg):
self.sock.sendall(msg)
def rec_message(self):
while self.accepting:
print self.sock.recv(1024)
# Criar objeto da classe cliente
HOST = '127.0.0.1'
PORT = 38267
client = Client(HOST, PORT)
client.start()
msg = raw_input()
while msg <> '/quit':
client.send_message(msg)
msg = raw_input()
client.close()