一个简单的聊天小程序,做了个简单的界面,本机试了下,应该没什么大问题。
server端:
client端:
本程序使用了python的线程模块threading,server端为每个连接创建一个线程处理读写操作。client端则创建一个子线程处理接收客户端的数据。
client端的recvThreading线程调用了setDeamon(True)方法,作用是主线程结束时,子线程也一起结束,使gui不是‘卡死’
界面方面尝试了之前看到过的可扩展对话框。
问题:
一开始,我是将接收到的信息直接append到QTextEdit上面去了,这样做会出现一个警告:
QObject::connect: Cannot queue arguments of type 'QTextCursor'
(Make sure 'QTextCursor' is registered using qRegisterMetaType().)
上网查了一下说,使用多线程的时候不能在子线程append,所以设置了messages变量来存储新的信息,用一个QTimer对象触发timeout信号,再将messages变量的信息在主线程append上去QTextEdit对象。
server code:
#!/usr/bin/evn python
#coding:utf-8
import socket
import threading
host = 'localhost'
port = 8805
username = ''
clients = []
def server(sock, addr):
while 1:
try:
print 'waitting data...'
data = sock.recv(1024)
if not data:
break
for c in clients:
c.send(data)
print data
except:
break
clients.remove(sock)
sock.close()
print '[%s:%s] leave' % (addr[0], addr[1])
print clients
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket create'
s.bind((host, port))
s.listen(3)
print 'Socket is listenning...'
while 1:
client, addr = s.accept()
username = client.recv(1024)
clients.append(client)
print '[%s:%s:%s] join!' % (addr[0], addr[1], username)
print clients
thread = threading.Thread(target = server, args = (client, addr))
thread.start()
client code: #!/usr/bin/evn python
#coding:utf-8
import socket
import threading
import sys
import time
from PyQt4 import QtCore as core
from PyQt4 import QtGui as gui
host = 'localhost'
port = 8805
username = 'Default'
class Client(gui.QWidget):
def __init__(self, parent = None):
super(Client, self).__init__(parent)
self.setWindowTitle('CLient')
self.setNameWidget = gui.QWidget()
self.layout = gui.QGridLayout(self)
self.setNameLayout = gui.QGridLayout(self.setNameWidget)
self.btnSend = gui.QPushButton('send')
self.btnSet = gui.QPushButton('Set')
self.input = gui.QLineEdit()
self.name = gui.QLineEdit('Default')
self.chat = gui.QTextEdit()
self.label = gui.QLabel('name:')
self.timer = core.QTimer()
self.messages = []
self.build()
self.createAction()
recvThread = threading.Thread(target = self.recvFromServer)
recvThread.setDaemon(True)
recvThread.start()
def sendToServer(self):
global username
text = str(self.input.text())
self.input.setText('')
if text == 'q':
self.exit()
elif text.strip() == '':
return
try:
s.send('%s: %s' % (username, text))
print '%s >> %s' % (username, text)
except:
self.exit()
def recvFromServer(self):
while 1:
try:
data = s.recv(1024)
if not data:
exit()
self.messages.append(data)
except:
return
def showChat(self):
for m in self.messages:
self.chat.append(m)
self.messages = []
def slotExtension(self):
global username
name = str(self.name.text())
if name.strip() != '':
username = name
print username
self.setNameWidget.hide()
def exit(self):
s.close()
sys.exit()
def build(self):
self.layout.addWidget(self.chat, 0, 0, 5, 4)
self.layout.addWidget(self.input, 5, 0, 1, 4)
self.layout.addWidget(self.btnSend, 5, 4)
self.setNameLayout.addWidget(self.label, 0, 0)
self.setNameLayout.addWidget(self.name, 0, 1)
self.setNameLayout.addWidget(self.btnSet, 0, 4)
self.layout.addWidget(self.setNameWidget, 6, 0)
self.layout.setSizeConstraint(gui.QLayout.SetFixedSize)
def createAction(self):
self.btnSend.clicked.connect(self.sendToServer)
self.btnSet.clicked.connect(self.slotExtension)
self.timer.timeout.connect(self.showChat)
self.timer.start(1000)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send(username)
print '[%s] connect' % username
app = gui.QApplication(sys.argv)
c = Client()
c.show()
app.exec_()