Showing posts with label Junk characters in recv return. Show all posts
Showing posts with label Junk characters in recv return. Show all posts

Friday, January 30, 2009

More on TCP/IP streaming Sockets

tcp-ip-streaming-sockets-diagram

I was writing server side code which will be reading commands from a client over a Win32 socket, problematic code was like this

// suppose m_sock is a working socket, all we gotta do is start receiving data on it

const int nBuffSize = 256;
int nRecv = 0;
char * szCmdBuff = new char [nBuffSize];
memset(szCmdBuff, 0, nBuffSize);
while(1){
nRecv = recv(m_sock, szCmdBuff, nBuffSize, 0);
// do something with the data
memset(szCmdBuff, 0, nBuffSize);
}

Problem created by this code: Junk values in input.
Solution: do memset right before calling recv

Exact code to refresh things goes like this

while(1){
memset(szCmdBuff, 0, nBuffSize);
nRecv = recv(m_sock, szCmdBuff, nBuffSize, 0);
// do something with the data
memset(szCmdBuff, 0, nBuffSize);
}

TCP IP sockets are the foundation rock of http protocol, which is the core of internet today. Having a solid understanding of how TCP/IP sockets work is essential to solve network communications problems.

cheers all...