赞
踩
python实现的聊天室(二)
1、前言
我在python实现的聊天室(一)一文中实现了一个没有界面的聊天室,所有操作都在CMD命令行下进行,用户体验比较差。所以在这一篇文章中,主要实现一个有界面的聊天室。
2、需求分析
我们要实现的分为两部分:
服务器:负责与用户建立 Socket 连接,并将某个用户发送的消息广播到所有在线的用户。显示用户进入/退出聊天室信息。
客户端:可以输入聊天的内容并发送,同时可以显示其他用户的消息记录。
3、服务端实现
# -*- coding: gbk -*-
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
from PyQt4.QtNetwork import *
import locale
#QTextCodec.setCodecForTr(QTextCodec.codecForName("utf8"))
class TcpClientSocket(QTcpSocket):
def __init__(self,parent=None):
super(TcpClientSocket,self).__init__(parent)
self.connect(self,SIGNAL("readyRead()"),self.dataReceive)
self.connect(self,SIGNAL("disconnected()"),self.slotDisconnected)
self.length = 0
self.msglist = QByteArray()
def dataReceive(self):
while self.bytesAvailable() > 0:
length = self.bytesAvailable()
msg = self.read(length)
self.emit(SIGNAL("updateClients(QString,int)"),msg,length)
def slotDisconnected(self):
pass
class Server(QTcpServer):
def __init__(self,parent=None,port=0):
super(Server,self).__init__(parent)
self.listen(QHostAddress.Any,port)
self.tcpClientSocketList = []
def incomingConnection(self,socketDescriptor):
tcpClientSocket = TcpClientSocket(self)
self.connect(tcpClientSocket,SIGNAL("updateClients(QString,int)"),self.updateClients)
self.connect(tcpClientSocket,SIGNAL("disconnetcted(int)"),self.slotDisconnected)
tcpClientSocket.setSocketDescriptor(socketDescriptor)
self.tcpClientSocketList.append(tcpClientSocket)
def updateClients(self,msg,length):
self.emit(SIGNAL("updateServer(QString,int)"),msg,length
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。