QT网络编程网络编程Tcp下下C/S架构的即时通信实例架构的即时通信实例
先写一个客户端,实现简单的,能加入聊天,以及加入服务器的界面。
#ifndef TCPCLIENT_H
#define TCPCLIENT_H
#include <QDialog>
#include <QListWidget>
#include <QLineEdit>
#include <QPushButton>
#include <QLabel>
#include <QGridLayout>
#include <QtNetWork/QHostAddress>
#include <QtNetWork/QTcpSocket>
class TcpClient : public QDialog
{
Q_OBJECT
public:
TcpClient(QWidget *parent = 0,Qt::WindowFlags f=0);
~TcpClient();
private:
QListWidget *contentListWidget;
QLineEdit *sendLineEdit;
QPushButton *sendBtn;
QLabel *userNameLabel;
QLineEdit *userNameLineEdit;
QLabel *serverIPLabel;
QLineEdit *serverIPLineEdit;
QLabel *portLabel;
QLineEdit *portLineEdit;
QPushButton *enterBtn;
QGridLayout *mainLayout;
bool status;
int port;
QHostAddress *serverIP;
QString userName;
QTcpSocket *tcpSocket;
public slots:
void slotEnter();
void slotConnected();
void slotDisconnected();
void dataReceived();
void slotSend();
};
#endif // TCPCLIENT_H
有一个加入服务器的按钮,还有一个发送消息的按钮,在头文件,先定义两个函数。
#include "tcpclient.h"
#include <QMessageBox>
#include <QHostInfo>
TcpClient::TcpClient(QWidget *parent,Qt::WindowFlags f)
: QDialog(parent,f)
{
setWindowTitle(tr("TCP Client"));
contentListWidget = new QListWidget;
sendLineEdit = new QLineEdit;
sendBtn = new QPushButton(tr("send"));
userNameLabel = new QLabel(tr("name"));
userNameLineEdit = new QLineEdit;
serverIPLabel = new QLabel(tr("server"));
serverIPLineEdit = new QLineEdit;
portLabel = new QLabel(tr("port"));
portLineEdit = new QLineEdit;
enterBtn= new QPushButton(tr("join chat"));
评论0