C++ - Winsock server receiving distorted buffer

I am trying to repetitively send the screen bitmap buffer of a client to a server. The program works perfect when the client and server are running on the same machine, otherwise the server receives a distorted buffer. The distorted buffer received by the server seems to start from a byte which was not the starting byte of a buffer sent by the client (I am not sure). w=1366 and h=768 are the screen width and height respectively of both the server and the client.

Client code:

1
2
3
4
5
6
7
8
9
10
11
while (connect(sSocket,(sockaddr*)&addr,sizeof(addr))!=0) {}

while (!GetAsyncKeyState(VK_ESCAPE)) {
    s=4*w*h;
    while (s>0) {
        n=send(sSocket,buf,s,0); s-=n;
        for (i=0; i<s; i++) {buf[i]=buf[i+n];}
    }
    BitBlt(MemDC,0,0,w,h,hdc,0,0,SRCCOPY);
    GetDIBits(MemDC,hBit,0,h,buf,&bmi,DIB_RGB_COLORS);
}


Server code:

1
2
3
4
5
6
7
do {rSocket=accept(hSocket,(sockaddr*)&addr,&addrlen);}
while (rSocket==INVALID_SOCKET);

while (!GetAsyncKeyState(VK_ESCAPE)) {
    s=4*w*h; while (s>0) {n=recv(rSocket,buf,s,0); s-=n;}
    SetDIBitsToDevice(hdc,0,0,w,h,0,0,0,h,buf,&bmi,DIB_RGB_COLORS);
}


I have been changing my code in many ways hoping to get the problem fixed, but it has been two weeks and it is still there. The problem is with such a simple code, yet I couldn't find any post related to it. I'd be really grateful if anyone helped.
on line 5 in your Server code: how do you know w and h?
if you receive the data in smaller packets you do not increase buf. That means you will get the last packet in buf only
I have only shown the part of my code after and including the time of connection. I had declared w and h previously.

"you do not increase buf"

Was that meant as something for me to do or something that is done? buf is declared as a char buffer with size 4*w*h
Last edited on
Change line 5 to s=4*w*h; while (s>0) {n=recv(rSocket,buf,s,0); s-=n; buf += n; }
Thanks a lot... that worked! What exactly does buf+=n; do? I googled but I couldn't find anything related to it.
Topic archived. No new replies allowed.