QT network programming: instant communication in the C/S architecture under Tcp, and qt Network Programming

Source: Internet
Author: User

QT network programming: instant communication in the C/S architecture under Tcp, and qt Network Programming

First, write a client, which is simple, can join the chat, and join the server interface.

#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_OBJECTpublic:    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

There is a button to add to the server and a button to send messages. In the header file, two functions are defined first.

# 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"); serv ErIPLineEdit = new QLineEdit; portLabel = new QLabel (tr ("port"); portLineEdit = new QLineEdit; enterBtn = new QPushButton (tr ("join chat ")); mainLayout = new layout (this); mainLayout-> addWidget (contentListWidget,); mainLayout-> addWidget (sendLineEdit,); mainLayout-> addWidget (sendBtn ); mainLayout-> addWidget (userNameLabel, 2, 0); mainLayout-> addWidget (userNameLineEdit, 2, 1); mainLayout -> AddWidget (serverIPLabel,); mainLayout-> addWidget (Region,); mainLayout-> addWidget (portLabel,); mainLayout-> addWidget (portLineEdit ); mainLayout-> addWidget (enterBtn, 8010, 0,); status = false; port =; portLineEdit-> setText (QString: number (port )); serverIP = new QHostAddress (); connect (enterBtn, SIGNAL (clicked (), this, SLOT (slotEnter (); connect (sendBtn, SIGNAL (clicked (), this, SLOT (slotSend (); sendBtn-> setEnabled (false);} TcpClient ::~ TcpClient () {} void TcpClient: slotEnter () {if (! Status) {QString ip = serverIPLineEdit-> text (); if (! ServerIP-> setAddress (ip) {QMessageBox: information (this, tr ("error"), tr ("server ip address error! "); Return;} if (userNameLineEdit-> text () =" ") {QMessageBox: information (this, tr (" error "), tr ("User name error! "); Return;} userName = userNameLineEdit-> text (); tcpSocket = new QTcpSocket (this); connect (tcpSocket, SIGNAL (connected (), this, SLOT (slotConnected (); connect (tcpSocket, SIGNAL (disconnected (), this, SLOT (slotDisconnected (); connect (tcpSocket, SIGNAL (readyRead ()), this, SLOT (dataReceived (); tcpSocket-> connectToHost (* serverIP, port); status = true;} else {int length = 0; QString msg = userName + tr (": Leave C Hat Room "); if (length = tcpSocket-> write (msg. toLatin1 (), msg. length ()))! = Msg. length () {return;} tcpSocket-> disconnectFromHost (); status = false;} void TcpClient: slotConnected () {sendBtn-> setEnabled (true ); enterBtn-> setText (tr ("exit"); int length = 0; QString msg = userName + tr (": Enter Chat Room "); if (length = tcpSocket-> write (msg. toLatin1 (), msg. length ()))! = Msg. length () {return ;}} void TcpClient: slotSend () {if (sendLineEdit-> text () = "") {return ;} QString msg = userName + ":" + sendLineEdit-> text (); tcpSocket-> write (msg. toLatin1 (), msg. length (); sendLineEdit-> clear ();} void TcpClient: slotDisconnected () {sendBtn-> setEnabled (false ); enterBtn-> setText (tr ("join chat");} void TcpClient: dataReceived () {while (tcpSocket-> bytesAvailable ()> 0) {QByteArray datasync; datasync. resize (tcpSocket-> bytesAvailable (); tcpSocket-> read (datax. data (), datax. size (); QString msg = datax. data (); contentListWidget-> addItem (msg. left (datax. size ()));}}

Implement the interface layout. In the Enter slot function, determine whether to add or exit the server function. If the message is added, the message is written to the tcpsocket and the structure is eliminated.

Server header file:

#ifndef TCPSERVER_H#define TCPSERVER_H#include <QDialog>#include <QListWidget>#include <QLabel>#include <QLineEdit>#include <QPushButton>#include <QGridLayout>#include "server.h"class TcpServer : public QDialog{    Q_OBJECTpublic:    TcpServer(QWidget *parent = 0,Qt::WindowFlags f=0);    ~TcpServer();private:    QListWidget *ContentListWidget;    QLabel *PortLabel;    QLineEdit *PortLineEdit;    QPushButton *CreateBtn;    QGridLayout *mainLayout;    int port;    Server *server;public slots:    void slotCreateServer();    void updateServer(QString,int);};#endif // TCPSERVER_H

This is the interface of the server. It only displays the message. Implement this layout.

#include "tcpserver.h"TcpServer::TcpServer(QWidget *parent,Qt::WindowFlags f)    : QDialog(parent,f){    setWindowTitle(tr("TCP Server"));    ContentListWidget = new QListWidget;    PortLabel = new QLabel(tr(" port"));    PortLineEdit = new QLineEdit;    CreateBtn = new QPushButton(tr("create chat"));    mainLayout = new QGridLayout(this);    mainLayout->addWidget(ContentListWidget,0,0,1,2);    mainLayout->addWidget(PortLabel,1,0);    mainLayout->addWidget(PortLineEdit,1,1);    mainLayout->addWidget(CreateBtn,2,0,1,2);    port=8010;    PortLineEdit->setText(QString::number(port));    connect(CreateBtn,SIGNAL(clicked()),this,SLOT(slotCreateServer()));}TcpServer::~TcpServer(){}void TcpServer::slotCreateServer(){    server = new Server(this,port);    connect(server,SIGNAL(updateServer(QString,int)),this,SLOT(updateServer(QString,int)));    CreateBtn->setEnabled(false);}void TcpServer::updateServer(QString msg,int length){    ContentListWidget->addItem(msg.left(length));}

Create a TCP socket for communication between the server and the client.

#ifndef TCPCLIENTSOCKET_H#define TCPCLIENTSOCKET_H#include <QtNetWork/QTcpSocket>#include <QObject>class TcpClientSocket : public QTcpSocket{    Q_OBJECTpublic:    TcpClientSocket();signals:    void updateClients(QString,int);    void disconnected(int);protected slots:    void dataReceived();    void slotDisconnected();};#endif // TCPCLIENTSOCKET_H

The above is the header file, specifically:

#include "tcpclientsocket.h"TcpClientSocket::TcpClientSocket(){    connect(this,SIGNAL(readyRead()),this,SLOT(dataReceived()));    connect(this,SIGNAL(disconnected()),this,SLOT(slotDisconnected()));}void TcpClientSocket::dataReceived(){    while(bytesAvailable()>0)    {        int length = bytesAvailable();        char buf[1024];        read(buf,length);        QString msg=buf;        emit updateClients(msg,length);    }}void TcpClientSocket::slotDisconnected(){    emit disconnected(this->socketDescriptor());}

Implementation server, header file:

#ifndef SERVER_H#define SERVER_H#include <QtNetWork/QTcpServer>#include <QObject>#include "tcpclientsocket.h"class Server : public QTcpServer{    Q_OBJECTpublic:    Server(QObject *parent=0,int port=0);    QList<TcpClientSocket*> tcpClientSocketList;signals:    void updateServer(QString,int);public slots:    void updateClients(QString,int);    void slotDisconnected(int);protected:    void incomingConnection(int socketDescriptor);};#endif // SERVER_H

  

#include "server.h"Server::Server(QObject *parent,int port)    :QTcpServer(parent){    listen(QHostAddress::Any,port);}void Server::incomingConnection(int socketDescriptor){    TcpClientSocket *tcpClientSocket = new TcpClientSocket;    connect(tcpClientSocket,SIGNAL(updateClients(QString,int)),this,SLOT(updateClients(QString,int)));    connect(tcpClientSocket,SIGNAL(disconnected(int)),this,SLOT(slotDisconnected(int)));    tcpClientSocket->setSocketDescriptor(socketDescriptor);    tcpClientSocketList.append(tcpClientSocket);}void Server::updateClients(QString msg,int length){    emit updateServer(msg,length);    for(int i=0;i<tcpClientSocketList.count();i++)    {        QTcpSocket *item = tcpClientSocketList.at(i);        if(item->write(msg.toLatin1(),length)!=length)        {            continue;        }    }}void Server::slotDisconnected(int descriptor){    for(int i=0;i<tcpClientSocketList.count();i++)    {        QTcpSocket *item = tcpClientSocketList.at(i);        if(item->socketDescriptor()==descriptor)        {            tcpClientSocketList.removeAt(i);            return;        }    }    return;}

After implementation:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.