[Qt] Chat room implementation based on TCP protocol

Source: Internet
Author: User
Tags socket port number

Date: June 21, 2017


first, write in front:

Usually do more graphics learning things, although the network programming is very interested, but there is no chance to try. Recently just in time to catch up with the final course internship, and then refer to the official QT network programming References, wrote a LAN group chat software, but also relatively good-looking bar ~, because it is their own submission of the job, so relatively humble will, the main features are:

(1) User registration and Login

(2) Multi-user join chat room chat.

(3) Retrieve password and other service functions.


second, before the beginning of the text, first put my implementation results:

(1) "Client" chat room Chat interface

Contains basic information for the user, Chat window, current online user table. The screenshot has four users online at the same time.


(2) "Server"

Responsible for the management of user information, forwarding chat messages and other functions. The screenshot is the server state at the moment above.



(3) "Client" User login


three, "principle" based on QT implementation of the TCP protocol chat room simple demo 1. About the TCP protocol:

TCP protocol is a connection-oriented, reliable, byte-stream-based Transport layer communication protocol. QT offers a simple package that can be easily implemented with Windows API or Linux <sys/socket.h>.

The TCP protocol is known as a connection-oriented communication protocol. The reason is that the transport of the TCP protocol relies on a TCP connection . A TCP connection, consisting of two sockets, located at both ends of the data transfer (in this case, the client, the server), and the byte stream data sends a pair of messages over a TCP connection. 2. Communication flow of chat room:

First, start one server (server) and make it listen on (listen) a port on the server side.

When the server receives a "make connection" request from a client's socket, the server creates a local proxy for the client socket (also a socket) locally, so that a TCP connection is created successfully. Of course, the server can send messages to the server through this local proxy (socket), and the client can send messages through its own socket to the server-side proxy socket.

If you allow multiple clients to connect to the server, you can manage all server-side sockets with a single list.

I drew a flowchart of the above process, as follows:


3. TCP Communication in QT

In QT, sockets are supported by Qtcpsocket and the server is supported by Qtcpserver. Specific information about these classes can be queried in the official QT Help document (QT assistance).

Before using QT's network module, you need to connect the QT library file. In the pro file, you can add the following code implementation:

QT + = Network

The main functions of the "3.1"qtcpserver :

BOOLqtcpserver::listen(const qhostaddress& address = qhostaddress::any, Quint16port = 0);

[Qt assistance] Tells the server to listen for incoming connections on address and port. If Port is 0, a port is chosen automatically. If address is qhostaddress::any, the server would listen on all network interfaces. Returns true on success; otherwise returns false.

Tell the server where he wants to listen for connections and ports. If address is qhostaddress::any,server will listen for all network connection requests, Port can take any port number that is not occupied (for example: 19999)

qtcpsocket* qtcpserver::nextpendingconnection()

[Qt assistance] Returns the next pending connection as a connected Qtcpsocket object.

Returns the next socket that the server has requested to establish a connection but has not yet processed.

The main functions of the "3.2"qtcpsocket :

voidqsocket::connecttohost(const qhostaddress & address, quint16 port, OpenMode openmode = ReadWrite)

[Qt assistance] Attempts to make a connection to address on port.

Try to connect to a server with an IP address of port, and the ports.

voidQabstractsocket::abort ()

[Qt assistance] Aborts the current connection and resets the socket.

Interrupts the current connection and resets the socket.

Read and write operations: Qtcpsocket::write (const char*), Qtcpsocket::writeall (const char*)


4. A simple demo-specific code and download connection for a LAN chat room based on the TCP protocol:

Demo program Download connection: http://download.csdn.net/detail/mahabharata_/9877757

Demo program feature brief: This example contains two programs for TcpClient and TCPServer. TcpClient is a communication client, can be opened at the same time multiple, tcpserver for the server, for the relay and forwarding of messages.

Demo Program demonstration diagram:


Skeleton Code for demo program:

(1) Client program TcpClient

Program: TcpClient
//header file: ClientWindow.h

#ifndef clientwindow_h
#define CLIENTWINDOW_H

#include < qmainwindow>
#include <QTcpSocket>
#include <QHostAddress>

namespace Ui {
class Clientwindow;
}

Class Clientwindow:public Qmainwindow
{
    q_object public

:
    explicit Clientwindow (Qwidget *parent = 0);
    ~clientwindow ();

    qtcpsocket* M_socket;      Client socket

    void Connecttoserver ();    Connect to server

private slots:
    void Slot_readmessage ();   Processing the message sent by the receiving server
    void Slot_btnsendmsg ();    After clicking the Send button, send the message


private:
    Ui::clientwindow *ui;
};

#endif//Clientwindow_h

Program: TcpClient//source file: ClientWindow.cpp #include "clientwindow.h" #include "ui_clientwindow.h" Clientwindow::

    Clientwindow (Qwidget *parent): Qmainwindow (parent), UI (new Ui::clientwindow) {ui->setupui (this);
    Connecttoserver ();

    Do and Things} void Clientwindow::connecttoserver () {m_socket = new Qtcpsocket (this); Connect to server//try to connect to IP as "127.0.0.1" & Port number 19999 Server//If you want to implement LAN communication, simply set the first IP address to the IP address of the host on which the server is located//such as M_sock
    Et->connecttohost ("170.29.19.65", 19999);

    M_socket->connecttohost (Qhostaddress::localhost, 9999);   Connect (m_socket,signal (Readyread ()), This,slot (Slot_readmessage ()));

    Tell the socket to use Slot_readmessage () to process the received message.
Connect (ui->pushbutton,signal (clicked ()), This,slot (Slot_btnsendmsg ()));


    } void Clientwindow::slot_readmessage ()//will only be called when the socket receives the server message {QString str = M_socket->readall (). data ();
Ui->textbrowser->settext (Ui->textbrowser->toplaintext () + "\ n" + str); } VOID clientwindow::slot_btnsendmsg () {QString str = ui->lineedit->text ();    M_socket->write (Str.tostdstring (). data ());
Exception ui->lineedit->clear ();
 } clientwindow::~clientwindow () {Delete UI;}

(2) server-side program: TCPServer

Program: TcpClient
//header file: ServerWindow.h

#ifndef serverwindow_h
#define SERVERWINDOW_H

#include < qmainwindow>
#include <QTcpSocket>
#include <QTcpServer>

namespace Ui {
class Serverwindow;
}

Class Serverwindow:public Qmainwindow
{
    q_object public

:
    explicit Serverwindow (Qwidget *parent = 0);
    ~serverwindow ();

    qtcpserver* M_server;

    Qlist<qtcpsocket*> m_sockets;   All customers connected to the server.  Linked list mode, a backup on the server side (client socket)

    void StartServer ();    Start a server public
slots:
    void Slot_newconnection ();  connecttohost () corresponding to the client;

    void Slot_readmessage ();   Each socket binding


private:
    Ui::serverwindow *ui;
};

#endif//Serverwindow_h


Program: TcpClient//source file: ServerWindow.cpp #include "serverwindow.h" #include "ui_serverwindow.h" Serverwindow::

    Serverwindow (Qwidget *parent): Qmainwindow (parent), UI (new Ui::serverwindow) {ui->setupui (this);
StartServer ();

    } void Serverwindow::startserver () {m_server = new qtcpserver (this);

    M_server->listen (Qhostaddress::any, 19999);  Connect (m_server,signal (Newconnection ()), This,slot (Slot_newconnection ())); } void Serverwindow::slot_newconnection () {//Put the newly added socket into the list qtcpsocket* socket = M_SERVER-&GT;NEXTPENDINGC

    Onnection ();

    M_sockets.push_back (socket);
Connect (socket,signal (Readyread ()), This,slot (Slot_readmessage ()));  }//Each socket handles the function that receives the message void Serverwindow::slot_readmessage () {qtcpsocket* socket = (qtcpsocket*) qobject::sender ();

    Gets which socket received the message QString str = Socket->readall (). data ();
    for (int i=0; i<m_sockets.size (); i++) {M_sockets[i]->write (str.tostdstring (). data ()); }
} serverwindow::~serverwindow () {Delete UI;}
 


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.