Target, QT program as a client, Windows under Winsock as a server side, to achieve both ends of communication.
A small function test was written at the beginning:
[CPP] View plain
Copy
Qtcpsocket Tmpsock;
Tcpsock.connecttohost ("59.64.159.87", 7716);
Tcpsock.write (Buf,strlen (BUF) +1);
Msleep (3000);
Tcpsock.disconnect ();
The test results found that the client could only connect to the server side, and the server side could not receive messages from the client.
The initial speculation may be that QT's socket mechanism makes the socket buffer queue not immediately sent.
Another way:
[Cpp:showcolumns] View Plain
Copy
········· 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150
Qtcpsocket Tmpsock;
char* buf = "Hello";
Tcpsock.connecttohost ("59.64.159.87", 7716);
Tcpsock.write (Buf,strlen (BUF) +1);
Msleep (3000);
Tcpsock.disconnect ();
After running, the results are still incorrect. Start thinking about the qtsocket communication mechanism. The thought of this could be caused by qtcpsocket in a non-blocking way.
Find some information on the Internet.
Qtcpsocket because inherited from the qabstractsocket, so if do not take some measures, he is in the non-blocking mode, that is, event programming, there is a good thing is to implement a multi-link TCP link in a thread, save resources, but this way is more difficult to program.
For the first involved in this aspect of the friend is not quite suitable, all in the case of meeting the requirements or blocking the way the socket programming is relatively easy to understand, qabstractsocket inside provides several functions for blocking mode programming, the use of it can easily write a network application:
waitforconnected () Wait for the link to be established
Waitforreadyread () Waiting for new data to arrive
Waitforbyteswritten () waits for data to be written to the socket
Waitfordisconnected () waiting for link to break
When receiving data, we have a pattern to follow:
[C-sharp] View Plain
Copy
while (Socket.bytesavailable () < (int) nSize) {
if (!socket.waitforreadyread (Timeout)) {
Emit error (Socket.error (),
Socket.errorstring ());
Return
}
}
The main meaning of this passage is to wait for the arrival of the number of nsize, this is a must abide by the receiving data template, you can write it into an inline function, if the paragraph to meet the conditions, you can tolerate read reading.
Write a number, call write, and then call Waitforbyteswritten to determine whether the data is finished.
Then modify the original code.
[C-sharp] View Plain
Copy
Qtcpsocket Tmpsock;
char* buf = "Hello";
Tcpsock.connecttohost ("59.64.159.87", 7716);
Tcpsock.write (Buf,strlen (BUF) +1);
if (Tcpsock.waitforreadyread (3000))
Emit sockcondition ("successful");
Else
Emit Sockcondition ("failed");
Tcpsock.disconnect ();
Run Test success
http://blog.csdn.net/itjobtxq/article/details/8203809
Qtcpsocket blocking and non-blocking problems in communication programming