我很困惑,为什么QTcpSocket实例可以在官方示例中连接之前将文本发送到客户端。连接进来时,结果是:
New connection came
0
New connection ran into thread: 944
我的代码位于内容的底部,它基于官方示例[threadedfortuneserver.py]。
# -*- coding: utf-8 -*-
__author__ = 'erliang'
# TODO:消息处理以及UI响应
from PyQt4.QtCore import QThread, pyqtSignal
from PyQt4.QtGui import QMessageBox, QApplication
from PyQt4.QtNetwork import QTcpSocket, QTcpServer, QHostAddress
from ui import ServerWindow
class Socket(QTcpSocket):
def __init__(self, parent=None):
super(Socket, self).__init__(parent)
self.connected.connect(self.on_connected)
self.disconnected.connect(self.on_disconnected)
self.readyRead.connect(self.on_ready_read)
self.error.connect(self.on_error)
def on_connected(self):
print "Socket connected!"
def on_disconnected(self):
print "Socket disconnected!"
def on_ready_read(self):
print "Received data:", self.readAll()
def on_error(self):
print "Error occurred:", self.errorString()
class ChatThread(QThread):
error = pyqtSignal(QTcpSocket.SocketError)
def __init__(self, socketDescriptor, parent):
super(ChatThread, self).__init__(parent)
self.socketDescriptor = socketDescriptor
self.received_data = None
def run(self):
# 在此处新建线程处理客户端消息
self.tcp = Socket()
print self.tcp.state()
print "New connection ran into thread:", self.socketDescriptor
if not self.tcp.setSocketDescriptor(self.socketDescriptor):
self.error.emit(self.tcp.error())
return
# self.tcp.disconnectFromHost()
# self.tcp.waitForDisconnected()
class ChatServer(QTcpServer):
def __init__(self, parent=None):
super(ChatServer, self).__init__(parent)
self.newConnection.connect(self.on_new_connection)
def incomingConnection(self, socketDescriptor):
# print "New connection came!", socketDescriptor
self.thread = ChatThread(socketDescriptor, self)
self.thread.finished.connect(self.thread.deleteLater)
self.thread.start()
def on_new_connection(self):
print "New connection came"
class Server(ServerWindow):
def __init__(self):
super(Server, self).__init__()
self.StartServerButton.clicked.connect(self.start_server)
self.StopServerButton.clicked.connect(self.stop_server)
self.chat_server = ChatServer()
# self.ClientLogTable.setRowCount(2)
# self.ClientLogTable.setItem(1, 1, QTableWidgetItem('123'))
def start_server(self):
# GUi与Socket操作不能在同一线程, 每次打开服务器便新建一个线程
if not self.chat_server.isListening():
addr = QHostAddress()
addr.setAddress('127.0.0.1')
if not self.chat_server.listen(addr, 8888):
QMessageBox.critical(self, u"服务器", u"无法初始化服务器: %s." % self.server.errorString())
self.close()
return
self.InfoLabel.setText(u'服务器IP:{0} 端口:{1}'.format(self.chat_server.serverAddress().toString(),
self.chat_server.serverPort()))
def stop_server(self):
if self.chat_server.isListening():
self.chat_server.close()
self.InfoLabel.setText(u'服务器尚未启动!')
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
client = Server()
client.show()
sys.exit(app.exec_())