Fedora14 QT-based TCP text message chat room development records

Source: Internet
Author: User

I am confused about the TCP protocol. The reason is that the local and remote code of UDP is exactly the same after UDP is finished. It is only initialized in the constructor, and the bound local IP address is different. This function is automatically completed by getip. Therefore, local and remote operations are the same. However, this is not the case for TCP. I will summarize it here (my level is very low, but it is not an entry level for cainiao. To sum up, I just want to prevent myself from forgetting ):

I. server side:

The entire workflow is as follows:

The core part of the program isTcpnewconnect ()In this function, the slot function is triggered when the server receives the connection. This function is implemented as follows:

// The server's response slot function when the server listens to the Client Connection
Void Widget: tcpnewconnect ()
{
Qmessagebox box;
Box. settext ("tcp client, request connection ....");
Box.exe C ();
Tcpsocketserver = tcpserver-> nextpendingconnection ();
Connect (tcpsocketserver, signal (readyread (), this, slot (tcpreadmesg ()));
Connect (ui-> tcpsendbutton, signal (clicked (), this, slot (tcpsendmesg ()));
UI-> tcpsendbutton-> setenabled (true );

}

At this time, the tcpsocketserver is instantiated. The tcpsocketserver is of the qtcpsocket type. I added the suffix server to the tcpsocket of the client. That is to say, tcpserver only serves as a listener,When it is listened to, a qtcpsocket is instantiated. The rest of the work is done by the qtcpsocket, including receiving and sending information.

// Receive information from the TCP End and display the slot function
Void Widget: tcpreadmesg ()
{
Qtextcodec * Tc = qtextcodec: codecforname ("UTF-8 ");
Qbytearray DATA = tcpsocketserver-> readall ();
Qstring STR = tc-> tounicode (data );

Qdatetime time;
Qstring timestr = time. currentdatetime (). tostring ("yyyy-mm-dd hh: mm: ss ddd ");

Autoscroll ();
UI-> gettextedit-> settextcolor (qcolor ("red "));
UI-> gettextedit-> insertplaintext ("remote" + remoteipstr + ":" + timestr + "-- TCP -- \ n ");
UI-> gettextedit-> settextcolor (qcolor ("black "));
UI-> gettextedit-> insertplaintext (STR + "\ n ");
Autoscroll ();
}

// The text sending slot function at the TCP End
Void Widget: tcpsendmesg ()
{
Autoscroll ();
Qstring STR = UI-> sendtextedit-> toplaintext ();
If (Str. Length () = 0)
{
Qmessagebox box;
Box. settext ("Enter the content and try again! ");
Box.exe C ();
}
Else
{
Qbytearray DATA = Str. toascii ();
// Qdebug () <STR;
Tcpsocketserver-> write (data );
Qdatetime time;
Qstring timestr = time. currentdatetime (). tostring ("yyyy-mm-dd hh: mm: ss ddd ");

UI-> gettextedit-> settextcolor (qcolor ("red "));
UI-> gettextedit-> insertplaintext ("local" + localipstr + ":" + timestr + "-- TCP -- \ n ");
UI-> gettextedit-> settextcolor (qcolor ("black "));
UI-> gettextedit-> insertplaintext (STR + "\ n ");
UI-> sendtextedit-> clear (); // after you click send, the content in the send edit box is cleared.
UI-> sendtextedit-> setfocus (); // The focus is in the send edit box.
Autoscroll ();
}
}

With UDP experience, these two functions are better, at least there will be no problem in encoding and decoding. The display and sending functions on the server and the acceptor are the same. Qbytearray data for receiving functions = tcpsocketserver-> readall (); tcpsocketserver-> write (data) for sending function write data; there is still a difference between qbytearray data and UDP sending and receiving. Of course, you can only send simple text. If you send large files, it is not that easy.

Ii. tcp client

The client only has one qtcpsocket * tcpsocket. In the constructor, tcpsocket = new qtcpsocket (this). We want to press the "Connect" button and the client sends a request for connection. The slot function of this button is:

// Client, press the slot function of the TCP button
Void Widget: on_starttcpbtn_clicked ()
{
Remoteipstr = UI-> ipedit-> text ();
Port = UI-> portedit-> text ();
Tcpsocket-> abort (); // cancel the original connection
Tcpsocket-> connecttohost (remoteipstr, port. toint ());
}

The core sentence is tcpsocket-> connecttohost (remoteipstr, port. toint (); note that remoteipstr is a qstring type variable. You can also write it as tcpsocket-> connecttohost ("192.168.2.211 ",
6665. You can also write remotehostaddr = new qhostaddress (remoteipstr); tcpsocket-> connecttohost (* remotehostaddr, port. toint (); this is no problem! It seems that QT is flexible.

In addition, four slot functions should be connected in the constructor of the client:

Connect (tcpsocket, signal (connected (), this,Slot (tcpisconnect ()));
// Slot function when connected

Connect (tcpsocket, signal (disconnected (), this,Slot (tcpfailconnect ()));
// Slot function for disconnecting

Connect (ui-> tcpsendbutton, signal (clicked (), this, slot (tcpsendmesg (); // send messages
Connect (tcpsocket, signal (readyread (), this, slot (tcpreadmesg (); // receives the message

Sending and receiving messages are the same as those above. The first two slot functions just bring up a prompt, as shown below:

Bool Widget: tcpisconnect ()
{
UI-> tcpsendbutton-> setenabled (true );
Qmessagebox box;
Box. settext ("congratulations, TCP connection has been established! ");
Box.exe C ();
Return true;
}
Void Widget: tcpfailconnect ()
{
UI-> tcpsendbutton-> setenabled (false );
Qmessagebox box;
Box. settext ("TCP Connection Failed. Please try again or use UDP to send it! ");
Box.exe C ();
}

Finally, let me summarize the QT-based TCP implementation in the beginning:

Only two classes are used: qtcpserver and qtcpsocket. The server uses one qtcpserver and one qtcpsocket. The client uses only one qtcpsocket. The function of qtcpserver is to listen to the connection of the other party. Therefore, you must set the listening port number or the specific IP address at the beginning. When a client is connected, qtcpserver calls tcpsocketserver
= Tcpserver-> nextpendingconnection (); to instantiate the qtcpsocket on the server side, and the rest of the sending and receiving tasks are handled by this qtcpsocket! The client uses qtcpsocket to send a connection request. When the connection is successful, a function is triggered.

 In a word, qtcpsocket is always responsible for sending and reading data !!! Qtcpsocket can also send connection requests. qtcpserver listens and obtains the qtcpsocket instance that sends the request.

The core code, highlighted in red.

Q: What if the server rejects connection requests if it does not want to connect to the client? It is estimated that a button should be added on the server, and some methods of qtcpserver are used in the Key Slot function to reject the request. Continue to study!



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.