anyone can tell me how to open a TCP connection and send data at the same time? I open the connection as follows: socket-> conectohost (host, port) I would like to send along with the order to open connection 6 integers. thank you very much
2 Answers
As far as I know, you need to wait for the connection to be established before you can send data via QTcpSocket. Would a combination like this work in your usecase?
socket->connectToHost(...);
if( socket->waitForConnected() ) {
socket->write("my_data");
}
2 Comments
user950489
Can not you do a write and then a connecting or should I do before connecting? Should I wait before the or as you tell me?
Robin
@user950489: You can try and see if your server receives the bytes. But even if it does, I'd strongly recommend against it: You don't start speaking on the phone while you still hear the beep and wait for your peer to pick up. It's dirty. -- You send data to a port that's not yet connected, I guess (I don't know) it may depend on the server's OS whether the data is queued until the connection is established... or whether the data is justed dropped, because the connection is not yet up. Maybe you tell us why you need to send immediately, perhaps there's a good other way to do it.
int array[] = {1,2,3,4,5,6};
int array_elements = sizeof(array) / sizeof(int);
socket->connectToHost("example.com", 12345);
if(socket->waitForConnected(1000)) {
qDebug("Connected.");
for(int n = 0; n < array_elements; n++)
socket->write((char*)(array + n * sizeof(int)), sizeof(int));
qDebug("6 integers sent. Eat that.");
socket->disconnectFromHost();
} else {
qDebug("Timeout.");
}
2 Comments
user950489
thank you very much but I can not write integers in a socket like this: socket-> write (array [i], sizeof (int)); I get error: C: \ ejemplos_qt \ teratermobile-build-simulator \ .. \ teratermobile \ cliente.cpp: 99: error: no matching function for call to 'QTcpSocket:: write (QString &, unsigned int)'
user950489
I can not write integers in a socket, socket->write(integer)