In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "how to realize network programming in Qt". In daily operation, I believe that many people have doubts about how to realize network programming in Qt. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "how to realize network programming in Qt". Next, please follow the editor to study!
1. Tcp/IP protocol suite and udp1, TCP/IP protocol family
TCP/IP is actually a cooperative communication family, which provides access for network communication. To facilitate the discussion of the TCP/IP protocol family, it is generally divided into three parts:
①, Internet Protocol (IP).
②, Transmission Control Protocol (TCP), and user Datagram Protocol (UDP).
③, a set of application protocols above TCP and UDP. They include: Telnet, File transfer Protocol (FTP), Domain name Service Protocol (DNS) and simple mail transfer program (SMTP).
2 、 udp
Udp protocol (user Datagram protocol), which is the exact opposite of TCP protocol. Provide unreliable, connectionless and Datagram-based services. Unreliability means that the UDP protocol cannot guarantee the correct transmission of data from the sender to the receiver. If the data is lost halfway, or if the destination discards the data through data verification, the applications of UDP protocol usually have to handle the logic of data confirmation, timeout retransmission and so on.
3. Summary of commonly used communication protocols
1.3.1 、 tcp/ip
Tcp only needs to know that it is a means of communication, and there is a udp, so what is the relationship between the two. TCP/IP protocol is a suite of protocols. It includes a lot of agreements. UDP is just one of them. The reason why it is named TCP/IP protocol, because TCP,IP protocol is two very important protocols, named after them two, tcp is to make a phone call, udp is to send text messages.
Ip (protocol for interconnection between networks). The foreign language is the foreign language abbreviation of Internet Protocol, and the Chinese abbreviation is "Network Association". Abbreviated to IP), you can access the network by setting the ip address, the most frequently used ip protocol is ipv4 (ip protocol v version 4), and there is a version of ipv6,ipv4 that is not enough. The Ipv4 version is 32-bit, which is generally divided into 4 segments. The memory is an unsigned 32-bit integer, and ipv6 is a 64-bit integer. You can know the difference between ipv4 and ipv6 through the number of bits, and how many addresses can be saved. It's just that users don't need to figure it out.
Now the commonly used ip is 127.0.0.1, dotted format (a string). The interval separated by the dot is a character. Ip addresses have three types of ABC addresses. The first three paragraphs are used to determine the router, to determine which route the host is connected to the perimeter network, and the last paragraph is used to determine the host, to determine how few hosts are on this router, a maximum of 255, and 0 is generally used as a gateway.
Ip also has a subnet mask.
Subnet mask (subnet mask), also known as netmask, address mask, subnet mask, is a bitmask used to indicate which bits of an IP address identify the subnet in which the host resides and which bits identify the host. The subnet mask cannot exist alone and must be used in conjunction with the IP address. The subnet mask has only one function, which is to divide an IP address into two parts: the network address and the host address. Subnet mask-the "all 1" bit mode that blocks the network portion of an IP address.
For Class An addresses, the default subnet mask is 255.0.0.0
The default subnet mask for class B addresses is 255.255.0.0
The default subnet mask for Class C addresses is 255.255.255.0.
The subnet mask is usually 255.255.255.0.
The first three paragraphs of the ip address determine the router, and the last paragraph is the host location. So the subnet mask is understood as the subnet mask code.
1.3.2 、 Socket
The PC corresponds to a host on the network, and there will be multiple processes on this PC that need to access the network, so it is necessary to have something to deal with the network on the operating system of the PC. Predecessors have defined a "socket" to specifically deal with the network (the combination of source IP address and destination IP address and source port number and destination port number is called socket). Split a host into N network ports (Port) there will be a total of 65536, the maximum range of short, among these ports, it should be noted that 0-5000 ports are generally not used for operating system processes to use. Generally speaking, a lower port is used, which is safer. Of course, some ports are also used. For example, port 8080 can also be used more often. A process can only occupy one port, not multiple processes can occupy the same port. A process can occupy multiple ports, or more strictly, a port can only be used by one process at a time. Two programs on the network exchange data through a two-way communication connection, one end of which is called a socket.
At least one pair of port numbers (socket) is required to establish a network communication connection. Socket is essentially a programming interface (API), the encapsulation of TCP/IP, TCP/IP should also provide an interface for programmers to do network development, which is the Socket programming interface. Commonly known as "sockets", which are used to describe IP addresses and ports, are handles to a communication chain that can be used to communicate between different virtual machines or different computers.
1.3.3. Tcp communication model
C hands s model, client (c) / server (s) model, one server to correspond to the processing of multiple clients, one-to-many relationship. The following steps are not specifically specified, which are required by both the server and the client:
1. Prepare to import all library functions according to your own language
two。 To determine the version information, to determine the socket version, ip has v4 and V6 versions.
3. Create a socket, using the socket function
4. Initialize the protocol address cluster
5. Bind, use the bind function to bind the protocol address cluster with socket, but not the client.
6. On the server side, you need to listen to the listen function, but the client does not need this step.
7. The server needs to accept the connection, and the client needs to connect to the server.
8. After the connection is complete, start to communicate and send and receive data
9. Close socket after the communication is completed
2. Tcp in Qt (only the code is shown here)
Add this network to the project .pro file before you start
1 、 tcpsever
Tcpsever.h
# ifndef WIDGET_H#define WIDGET_H# include # include / / Network Information # include / / id address # include / / tcp Protocol # include / / socket socket # include # include namespace Ui {class Widget;} class Widget: public QWidget {Q_OBJECT public: explicit Widget (QWidget * parent = 0); ~ Widget (); private slots: void on_pushButton_listen_clicked (); void on_pushButton_send_clicked (); void newconnectslot () / / Connect void readyRead_Slot (); / / read information void disconnected_Slot (); / / disconnect private slots: QString list_all_IPV4 (); private: Ui::Widget * ui; / / 2, set the object QTcpServer * tcpServer; QTcpSocket * tcpSocket;} of the server and receiving client; # endif / / WIDGET_H
Tcpsever.cpp
# include "widget.h" # include "ui_widget.h" Widget::Widget (QWidget * parent): QWidget (parent), ui (new Ui::Widget) {ui- > setupUi (this); / / 3. Create server object tcpSocket=NULL; tcpServer=new QTcpServer (this) / / 5. The server with client connection sends signals connect (tcpServer, SIGNAL (newConnection ()), this, SLOT (newconnectslot (); QMessageBox::information (this, "local networking port display", this- > list_all_IPV4 ());} Widget::~Widget () {delete ui } void Widget::on_pushButton_listen_clicked () {/ / 4, start listening QString sever_Address = ui- > lineEdit_address- > text (); quint16 port = ui- > lineEdit_port- > text (). ToInt (); QHostAddress host = QHostAddress (sever_Address) If (! tcpServer- > isListening ()) {/ / listening bound ip address if (! tcpServer- > listen (host,port)) {qDebug () close (); ui- > pushButton_listen- > setText ("start listening");} QString Widget::list_all_IPV4 () {QString str; QList list=QNetworkInterface::allAddresses () / / obtain the ip address foreach (QHostAddress address, list) {if (address.isNull ()) continue; QAbstractSocket::NetworkLayerProtocol portocol=address.protocol () of all network cards on this machine; / / extract only the IPv4 address if (portocollocation socket QAbstract SocketGroupIPv4Protocol) continue Str = str +'\ n\ t'+address.toString () +'\ n\ t\ t;} return str;}; void Widget::newconnectslot () {/ / 6, accept client tcpSocket = tcpServer- > nextPendingConnection () QString client_Info = "client:" + tcpSocket- > peerAddress (). ToString () + "+" port number: "+ QString::number (tcpSocket- > peerPort ()); ui- > textBrowser_clientInfo- > setText (client_Info) / / send signal and read correlation connect (tcpSocket, SIGNAL (readyRead ()), this, SLOT (readyRead_Slot (); / / disconnect signal association client connect (tcpSocket, SIGNAL (disconnected ()), this, SLOT (disconnected_Slot ();} Void Widget::on_pushButton_send_clicked () {if (tcpSocket! = nullptr) {if (tcpSocket- > isWritable ()) {QString send = ui- > plainTextEdit_sendInfo- > toPlainText (); QByteArray sendarr = send.toLocal8Bit (); / / conversion between local character set and Unicode tcpSocket- > write (sendarr) } void Widget::readyRead_Slot () {if (tcpSocket! = nullptr) {if (tcpSocket- > isReadable ()) {QByteArray recvAll = tcpSocket- > readAll (); / / read all data QString str = str.fromLocal8Bit (recvAll.data ()); ui- > textBrowser_recv- > append (str);} Void Widget::disconnected_Slot () {QMessageBox::information (this, "Client Close Signal", "customer leaving");}; 2. Tcpclient
Tcpclient,h
# ifndef WIDGET_H#define WIDGET_H# include # include / / Network Information # include / / id address # include / / tcp Protocol # include / / socket socket # include # include namespace Ui {class Widget;} class Widget: public QWidget {Q_OBJECT public: explicit Widget (QWidget * parent = 0); ~ Widget (); private slots: void on_pushButton_listen_clicked (); void on_pushButton_send_clicked (); void readyRead_Slot () / / read information void disconnected_Slot (); / / disconnect private: Ui::Widget * ui; QTcpSocket * client; bool socket_state;}; # endif / / WIDGET_H
Tcpclient.cpp
# include "widget.h" # include "ui_widget.h" Widget::Widget (QWidget * parent): QWidget (parent), ui (new Ui::Widget) {ui- > setupUi (this); client = new QTcpSocket (this); socket_state = false; connect (client, SIGNAL (disconnected ()), this, SLOT (disconnected_Slot () Connect (client, SIGNAL (readyRead ()), this, SLOT (readyRead_Slot ());} Widget::~Widget () {delete ui;} void Widget::on_pushButton_listen_clicked () {QString ipAddress = ui- > lineEdit_address- > text (); qint16 port = ui- > lineEdit_port- > text (). ToInt (); if (! socket_state) {client- > connectToHost (ipAddress,port) If (client- > waitForConnected (3000)) {/ / wait for 3 seconds, and false ui- > pushButton_listen- > setText ("disconnect") will be returned if not connected; socket_state = true;} else {qDebug () close (); QMessageBox::information (this, "message prompt", "already left!", QMessageBox::Yes); ui- > pushButton_listen- > setText ("connection") Socket_state = false;}} void Widget::readyRead_Slot () {QByteArray data=client- > readAll (); QString str=str.fromLocal8Bit (data.data ()); ui- > textBrowser_recv- > append (str);}; void Widget::disconnected_Slot () {qDebug () toPlainText (); QByteArray da = datastr.toLocal8Bit (); if (client- > isOpen () & client- > isValid ()) {client- > write (da);}}
3. Udp in QT
Initial operation is the same as TCP operation
Udp_test.h
# ifndef WIDGET_H#define WIDGET_H# include / / 1, including related header files # include # include # include namespace Ui {class Widget;} class Widget: public QWidget {Q_OBJECT public: explicit Widget (QWidget * parent = 0); ~ Widget (); private slots: void on_pushButtonSend_clicked (); void readyReadSlot (); void on_pushButtonCLose_clicked (); private: Ui::Widget * ui; / / 2, define udp object QUdpSocket * udpSocket;} # endif / / WIDGET_H
Udp_test.cpp
# include "widget.h" # include "ui_widget.h" Widget::Widget (QWidget * parent): QWidget (parent), ui (new Ui::Widget) {ui- > setupUi (this); / 3, create object udpSocket=new QUdpSocket (this); / / 4, associate read signal with slot connect (udpSocket,SIGNAL (readyRead ()), this,SLOT (readyReadSlot ());} Widget::~Widget () {delete ui } void Widget::on_pushButtonSend_clicked () {udpSocket- > writeDatagram (ui- > plainTextEdit_sendInfo- > toPlainText () .toLocal8Bit (), / / content QHostAddress (ui- > lineEditIp- > text ()), / / send ip ui- > lineEditPort- > text () .toInt ()) / / sent address} void Widget::on_pushButtonCLose_clicked () {udpSocket- > bind (ui- > lineEditPort_2- > text (). ToInt ());} void Widget::readyReadSlot () {quint64 size = udpSocket- > bytesAvailable (); / / read the message size QByteArray ba; ba.resize (size); QHostAddress address; quint16 port; udpSocket- > readDatagram (ba.data (), size,&address,&port); QString str = QString::fromLocal8Bit (ba.data ()) Ui- > textEdit_recvInfo- > append (str);}
At this point, the study of "how to achieve network programming in Qt" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.