网络聊天室的功能,现在我通过Qt提供的QTcpServer和QTcpSocket实现。
TCP是一种可靠的,面向连接,面向数据流的传输协议,适用于高层协议,其中高层协议包括HTTP,FTP,而TCP协议非常适合数据的连续传输。
聊天室分为服务器端和客户端,服务器程序可以创建一个聊天室,而客户端程序可以输入登入的用户名,服务器地址以及所使用的端口号码,然后进入聊天室,在聊天室中的每个用户都可以看到聊天记录。
接下来实现的是客户端的实现:
客户端:
main.cpp
#include<QApplication>
#include"tcpclient.h"
int main(int argc,char *argv[])
{
QApplication app(argc,argv);
QTranslator translator(0);
translator.load("tcpclient_wxj");
app.installTranslator(&translator);
TcpClient *tcpclient = new TcpClient();
tcpclient->show();
return app.exec();
}
tcpclient.h
#ifndef TCPCLIENT_H
#define TCPCLIENT_H
#include<QtGui>
#include<QtNetwork>
class TcpClient:public QDialog
{
Q_OBJECT
public:
TcpClient(QWidget *parent=0,Qt::WindowFlags f=0);
~TcpClient();
public:
QListWidget *ListWidgetContent;
QLineEdit *LineEditSend;
QPushButton *PushButtonSend;
QLabel *LabelUser;
QLineEdit *LineEditUser;
QLabel *LabelServerIP;
QLineEdit *LineEditServerIP;
QLabel *LabelPort;
QLineEdit *LineEditPort;
QPushButton *PushButtonEnter;
QString userName;
int port;
QHostAddress *serverIP;
QTcpSocket *tcpSocket;
bool status;
public slots:
void slotEnter();
void slotConnected();
void slotDisconnected();
void slotSend();
void dataReceived();
};
#endif
tcpclient.cpp
#include"tcpclient.h"
TcpClient::TcpClient(QWidget *parent,Qt::WindowFlags f):QDialog(parent,f)
{
QFont font("ZYSong18030",12);
setFont(font);
setWindowTitle(tr("TCP CLient"));
QVBoxLayout *vbMain = new QVBoxLayout(this); //这行开始是客户端的显示与控制
ListWidgetContent = new QListWidget(this);
vbMain->addWidget(ListWidgetContent);
QHBoxLayout *hb1 = new QHBoxLayout();
LineEditSend = new QLineEdit(this);
hb1->addWidget(LineEditSend);
PushButtonSend = new QPushButton(this);
PushButtonSend->setText(tr("Send"));
hb1->addWidget(PushButtonSend);
vbMain->addLayout(hb1);
QHBoxLayout *hb2 = new QHBoxLayout();
LabelUser = new QLabel(this);
LabelUser->setText(tr("User name:"));
hb2->addWidget(La