簡易網絡聊天室服務端.PNG
簡易網絡聊天室客戶端.PNG
一、服務端
(一)創建套接字進行監聽
//創建套接字 socket()
server = new QTcpServer(this);
//監聽,端口號:9999 bind(...), listen()
bool isOk = server->listen(QHostAddress::Any,9999);
//監聽失敗
if(false == isOk)
{
QMessageBox::warning(this,"監聽","監聽失敗");
return;
}
//當有客戶端鏈接時,觸發信號:newConnection()
connect(server,SIGNAL(newConnection()),this,SLOT(newClient()));
(二)連接客戶端
void Server::newClient()
{
QTcpSocket *client;
//取出鏈接套接字 accept()
client = server->nextPendingConnection();
connect(client,SIGNAL(readyRead()),this,SLOT(tcpRead()));
connect(client,SIGNAL(disconnected()),this,SLOT(disClient()));
clients.push_back(client);
}
(三)讀取信息并群發
void Server::tcpRead()
{
//哪一個QTcpSocketc對象可讀就會發出readyRead()信號,通過信號的發出者找到相應的對象
QTcpSocket *client = qobject_cast<QTcpSocket *>(sender());
QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
QString str = QHostAddress(client->peerAddress().toIPv4Address()).toString() + ": " + time;
ui->MessageBrowser->append(str);
ui->MessageBrowser->append(client->readAll());
//群發
QList<QTcpSocket *>::iterator it;
for(it = clients.begin();it != clients.end();it++)
(*it)->write(str.toUtf8());
}
(四)退出客戶端
void Server::disClient()
{
QTcpSocket *client = qobject_cast<QTcpSocket *>(sender());
clients.removeOne(client);
}
二、客戶端
(一)連接服務器
Client::Client(QWidget *parent) :
QWidget(parent),
ui(new Ui::Client)
{
ui->setupUi(this);
tcp = new QTcpSocket(this);
tcp->connectToHost("127.0.0.1",9999);
if(!tcp->waitForConnected(3000))
{
QMessageBox::warning(this,"錯誤","連接失敗");
return;
}
connect(tcp,SIGNAL(readyRead()),this,SLOT(tcpRead()));
connect(ui->sendpushButton,SIGNAL(clicked(bool)),this,SLOT(tcpSend()));
}
(二)讀取信息
void Client::tcpRead()
{
QString str;
str = tcp->readAll();
ui->textBrowser->append(str);
ui->textBrowser->moveCursor(QTextCursor::End);
ui->textBrowser->append(ui->sendlineEdit->text());
}
(三)發送信息
void Client::tcpSend()
{
QString str = ui->sendlineEdit->text();
tcp->write(str.toUtf8());
}
該聊天系統能實現群聊功能,即一個客戶端向服務器發送信息,服務器接受信息之后將接受的信息發給所有與服務器相連的客戶端。