Sockets: send/receive continuous stream of data?
Hey all,
I'm trying to create a TCP client app and TCP server app using C (sockets w/ linux and winsock with windows)
I think I have the opening/closing sockets part down for both apps. The problem I'm facing is figuring out how to send and receive the data. The info to be sent is a series of ever changing number values. To emulate what I'd actually need I was thinking I could create an endless loop that sent random number data (client end) to the server. Right now I'm only trying to send individual strings typed in by the user...however, I don't think I have a good idea of how to really put the data into a buffer to send and receive it.
Also really quick question... whenever I call accept(), subsequent terminal output becomes all weird. I need to specify a newline before and after each statement I printf or wierd stuff happens. Namely, I'll get a newline but no text. Any ideas why?
It'd be awesome if someone can help me create a skeleton for send/recv or give me a conceptual description of how to set up send/rcv for my situation. The code I've attached is for rx and tx (only the relevant portion of the application's code)... let me know if the rest is necessary.
Code:
//from client app (winsock)
//____________________________________________
// SEND data
char *txMsg = "Hello World!";
vRet = send (dataTx, txMsg, (int)strlen(txMsg), 0);
if (vRet == SOCKET_ERROR)
{
cout << "\nError sending data... Exiting";
cout << "\nsend failed with error: " << WSAGetLastError();
cout << "\n";
system("PAUSE");
closesocket(dataTx);
return 0;
}
else
{
cout << "Sent data.\n";
//return 0;
}
Code:
//from server app
{
//the accept function waits if there are no pending connections
dataTx = accept (dataRx, (struct sockaddr*)&remote, &remLen );
printf("\n");
printf("-> [Connected to client %s]", inet_ntoa(remote.sin_addr) );
printf("\n");
do
{
char *recvBuff;
recvBuff = malloc (4 * sizeof(char));
if (numBytes = recv (dataTx, recvBuff, recvBuffSize, 0) > 0)
{
printf("\n-> Bytes Received: %d \n", numBytes); //why always one?
printf("\n-> Message Received: %s \n", recvBuff);
if (!(strcmp(recvBuff, quitString)))
{ printf("\nshould quit\n");
exFlag = 1; }
free (recvBuff);
recvBuff = NULL;
}
} while (exFlag != 1);
printf("\n-> [Closed connection]\n");
close(dataTx);
}
Thanks!
d02