Hi,
Currently, I'm experimenting a bit with sockets. Currently, I'm writing a client-server thingy, using the TCP protocol and WinSock 2. I'm not using text, but binary.
A problem has popped up a few days ago. If a specific part of the data sent, a number of structs, it is only received half of the time. This is weird, I thought TCP had no dataloss, especially not when connecting through localhost? What basically happens is that the first byte of the block of memory the socket reads to is written over, but the bytes after that are left the way they are. The recv function unblocks though.
I won't post the code which sends the data (I'm quite sure the error wouldn't be in there, and it is just too much), but maybe there is something wrong in my initialization code?
Client side:
/* Create a socket */
aSocket::aSocket(const char *host, bInt port) {
if (!socketsInit)
initSockets();
int nret;
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
sockaddr.sin_family = AF_INET;
sockaddr.sin_port = htons(port);
sockaddr.sin_addr.s_addr = inet_addr(host);
nret = connect(sock, (LPSOCKADDR) &sockaddr, sizeof(SOCKADDR_IN));
if (nret != 0) {
bError("Could not connect to server");
}
}
Server side:
/* Creates a server socket */
aServerSocket::aServerSocket(int port) {
this->port = port;
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // init socket
if(sock == INVALID_SOCKET) { /* check socket is valid */
bErrorF("Socket failed, error code %i", WSAGetLastError());
return;
}
/* bind server socket to a port */
SOCKADDR_IN serverInfo;
serverInfo.sin_family = AF_INET;
serverInfo.sin_addr.s_addr = INADDR_ANY;
serverInfo.sin_port = htons(port);
int nret = bind(sock, (LPSOCKADDR) &serverInfo, sizeof(struct sockaddr));
if(nret == SOCKET_ERROR) {
bErrorF("Socket failed, error code %i", WSAGetLastError());
return;
}
if(listen(sock, 10) != 0) {
bError("listen() failed");
return;
}
}
My excuses for the bad commenting. If there is need for it, I'll comment it.
Thanks in advance,
- Polyphemus