Although it seems okay, but its not okay to pass a variable initialized with NULL as out parameter to a function.
For example, I was doing this once upon a time
SomeClass *objSomeClass = NULL;
SomeFunction(objSomeClass);
// where SomeFunction is supposed to return something in objSomeClass
// This code is correct by syntax, but created problems for me.
The right thing to do is
SomeClass * objSomeClass = new SomeClass();
SomeFunction(objSomeClass);
cheers all...
Friday, January 30, 2009
More on TCP/IP streaming Sockets
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...
Mistakes, not to be forgotten
Socket Programming:
Was writing a socket server few days back. The code was not working, it goes like(omitting error checks)
SOCKET g_sock_server;
g_sock_server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
bind(g_sock_server, (LPSOCKADDR) &g_addr_server, sizeof(g_addr_server));
listen(g_sock_server, SOMAXCONN);
SOCKADDR_IN addr_cli;
SOCKET s_cli;
int nSize = 0;
s_cli = accept(g_sock_server, (LPSOCKADDR)&addr_cli, &nSize);
if(s_cli == INVALID_SOCKET) return;
// rest of the code... say blah blah blah blah
The method accept will always return INVALID_SOCKET, guess why?
because of
int nSize = 0;
The fix is
int nSize = sizeof(addr_cli)
cheers all...
Was writing a socket server few days back. The code was not working, it goes like(omitting error checks)
SOCKET g_sock_server;
g_sock_server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
bind(g_sock_server, (LPSOCKADDR) &g_addr_server, sizeof(g_addr_server));
listen(g_sock_server, SOMAXCONN);
SOCKADDR_IN addr_cli;
SOCKET s_cli;
int nSize = 0;
s_cli = accept(g_sock_server, (LPSOCKADDR)&addr_cli, &nSize);
if(s_cli == INVALID_SOCKET) return;
// rest of the code... say blah blah blah blah
The method accept will always return INVALID_SOCKET, guess why?
because of
int nSize = 0;
The fix is
int nSize = sizeof(addr_cli)
cheers all...
Subscribe to:
Posts (Atom)