Thread: Only first line gets sent

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    932

    Only first line gets sent

    Im writing a Win32 chat program.
    When i retrieve two lines from the Listbox to send, only the first line gets sent.

    I checked the char* in send(), it contains both lines.

    The first line can be any length, it gets there so its not a problem with the size.

    I tried to loop recv() too, it received the first line several times but not the second.

    The worse is that i dont even know on which side is the problem.

    Any idea would be highly appreciated.
    Using Windows 10 with Code Blocks and MingW.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Get Wireshark
    That will tell you what's happening "on the wire".

    And saying "I use send() and recv()" isn't much good. Everyone uses them, and most people have success. You need to post some code in context if you want more than guesses.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    Thank you very much Salem, Wireshark showed me that its the client who doesnt send the second line.

    So to summer up: everything is in the buffer to send but only the first line gets sent.

    Here's the code, server and client in one file, its .cpp and it compiles with mingw.

    Code:
    #include <winsock2.h>
    #include <windows.h>
    #include <Windowsx.h>
    #include <string>
    #include <vector>
    #include <process.h>
    ///////////////////////////////
    #include <io.h>
    #include <fcntl.h>
    /////////////////////////////
    #include <iostream>
    using namespace std;
    
    #define IDB_TEXT1 101
    #define IDB_TEXT2 102
    #define Send      103
    #define Server    104
    #define Client    105
    #define Ip        106
    
    #define WM_CLIENT (WM_USER + 107)
    #define WM_SERVER (WM_USER + 108)
    #define DATA_BUFSIZE 1024
    
    HWND hwnd, hWin_1, hWin_2, hSend, hServer, hClient, hIp;
    HANDLE h;
    MSG Msg;
    HDC hdc;
    PAINTSTRUCT ps;
    char * IP = "192.168.1.4";
    unsigned int port = 666, Th1, Th2, Th3, Th4, i;
    char recbuf1[255] = {0}, recbuf2[255] = {0}, name[16] = {0};
    string str1, str2, buffer, buffer2 = "You > ", buffer3;
    
    SOCKET sock, Accept;
    sockaddr_in sockad;
    WPARAM wParam;
    DWORD RecvBytes;
    DWORD SendBytes;
    DWORD Flags;
    
    //////////////////////////SOCKINFO////////////////////////////
    
    typedef struct _SOCKET_INFORMATION
    {
       BOOL RecvPosted;
       CHAR Buffer[DATA_BUFSIZE];
       WSABUF DataBuf;
       SOCKET Socket;
       DWORD BytesSEND;
       DWORD BytesRECV;
       struct _SOCKET_INFORMATION *Next;
    
    } SOCKET_INFORMATION, *LPSOCKET_INFORMATION;
    
    LPSOCKET_INFORMATION SocketInfoList;
    LPSOCKET_INFORMATION SocketInfo;
    
    void CreateSocketInformation(SOCKET s)
    {
       LPSOCKET_INFORMATION SI;
    
       if ((SI = (LPSOCKET_INFORMATION) GlobalAlloc(GPTR, sizeof(SOCKET_INFORMATION))) == NULL)
       {
          cout <<"GlobalAlloc() failed with error " << GetLastError();
          return;
       }
       else
         cout <<"GlobalAlloc() for SOCKET_INFORMATION is OK!\n";
    
       // Prepare SocketInfo structure for use
       SI->Socket = s;
       SI->RecvPosted = FALSE;
       SI->BytesSEND = 0;
       SI->BytesRECV = 0;
       SI->Next = SocketInfoList;
       SocketInfoList = SI;
    }
    
    LPSOCKET_INFORMATION GetSocketInformation(SOCKET s)
    {
       SOCKET_INFORMATION *SI = SocketInfoList;
    
       while(SI)
       {
          if (SI->Socket == s)
             return SI;
          SI = SI->Next;
       }
       return NULL;
    }
    
    void FreeSocketInformation(SOCKET s)
    {
       SOCKET_INFORMATION *SI = SocketInfoList;
       SOCKET_INFORMATION *PrevSI = NULL;
    
       while(SI)
       {
          if (SI->Socket == s)
          {
             if (PrevSI)
                PrevSI->Next = SI->Next;
             else
                SocketInfoList = SI->Next;
             closesocket(SI->Socket);
             GlobalFree(SI);
             return;
          }
    
          PrevSI = SI;
          SI = SI->Next;
       }
    }
    
    ///////////////////////SOCKINFO END/////////////////////////////////////////
    
    string  EditBoxFileParser()
    {
            int iCount, i;
            WORD iLength, iOffset;
            vector<char> vLines;
            buffer3 = "";
            //Get Number of Lines in Edit Field
            iCount = SendMessage(hWin_2, EM_GETLINECOUNT, 0, 0);
    
            if(!iCount) return 0;
    
            for(i=0; i<iCount; i++)
            {
                iOffset =       SendMessage(hWin_2, EM_LINEINDEX, i, 0);
                iLength = (WORD)SendMessage(hWin_2, EM_LINELENGTH, iOffset, 0);
    
                buffer = "";
                vLines.clear();
                vLines.resize(iLength+1);
    
                CopyMemory(&vLines[0], &iLength, sizeof(WORD));
    
                SendMessage(hWin_2, EM_GETLINE, i, (LPARAM)&vLines[0]);
                vLines[iLength] = 0;
                buffer.assign(vLines.begin(), vLines.end());
                buffer += "\r\n";
                buffer3 += buffer;
    
                vLines.insert(vLines.begin(), buffer2.begin(), buffer2.end());
                SendMessage(hWin_1, LB_INSERTSTRING, -1, (LPARAM)&vLines[0]);
            }
    
            int EndIdx = GetWindowTextLength (hWin_2);
            SendMessage (hWin_2, EM_SETSEL, (WPARAM)0, (LPARAM)EndIdx);
            SendMessage (hWin_2, WM_CLEAR, 0, 0);
            SetFocus(hWin_2);
    
            //cout << buffer <<endl;
            return (buffer3);
    }
    
    /////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////
    
    void SendData()
    {
         buffer = EditBoxFileParser();
         send(sock, buffer.c_str(), strlen(buffer.c_str()), 0);
    }
    
    int WSA_and_socket()
    {
        WSADATA wsaData;
        if(WSAStartup( MAKEWORD(2, 2), &wsaData ) != 0 ){
                   cout <<"WSAStartup() failed with error " << WSAGetLastError(); exit(1);
        }
    
        //Create a socket
        if((sock = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP )) == INVALID_SOCKET ){
                   cout <<"socket() failed with error " << WSAGetLastError(); WSACleanup(); exit(1);
        }
    }
    
    void Connect()
    {
         WSA_and_socket();
    
         sockad.sin_family      = AF_INET;
         sockad.sin_addr.s_addr = inet_addr(IP);
         sockad.sin_port        = htons( port );
    
         if(connect(sock, (LPSOCKADDR)&sockad, sizeof(sockad)) == SOCKET_ERROR )
         {
             cerr << "ClientSocket: Failed to connect\n";
             cout<<WSAGetLastError()<<"\r\n";
             system("pause");
             WSACleanup();
             exit(13);
         }
         SendMessage(hWin_1, LB_INSERTSTRING, -1, (LPARAM)"CONNECTED TO SERVER...");
         //cout << "\nCONNECTED!\n\n";
         WSAAsyncSelect(sock, hwnd, WM_CLIENT, FD_WRITE|FD_READ|FD_CLOSE);
    
         EnableWindow(hClient, FALSE);
         EnableWindow(hServer, FALSE);
    }
    
    void Bind_and_Listen( int port )
    {
         WSA_and_socket();
    
         sockad.sin_family = AF_INET;
         sockad.sin_addr.s_addr = htonl(INADDR_ANY);
         sockad.sin_port = htons( port );
    
         if(WSAAsyncSelect(sock, hwnd, WM_SERVER, FD_ACCEPT|FD_CLOSE) == 0)
            cout<<"WSAAsyncSelect() is OK\n";
         else
            cout<<"WSAAsyncSelect() failed with error code "<< WSAGetLastError() << "\n";
    
         if ( bind (sock, (SOCKADDR*) &sockad, sizeof( sockad) ) == SOCKET_ERROR )
         {
             cerr << "ServerSocket: Failed to bind "<< WSAGetLastError();
             WSACleanup(); exit(1);
         }
    
         if (listen(sock, 5))
         {
           cout <<"listen() failed with error " << WSAGetLastError();
           WSACleanup(); exit(1);
         }
         SendMessage(hWin_1, LB_INSERTSTRING, -1, (LPARAM)"WAITING FOR CLIENT...");
    
    }
    
    //////////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////WNDPROC////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////
    
    LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
    {
      switch(msg){
                  case WM_CREATE:
                       hWin_1 = CreateWindowEx(0,"ListBox", 0,
                             WS_CHILD | WS_VISIBLE | WS_BORDER | ES_WANTRETURN |
                             LBS_NOTIFY | WS_VSCROLL,
                             20, 20, 550, 460, hwnd, (HMENU)IDB_TEXT1, 0, NULL);
                       hWin_2 = CreateWindowEx(0,"Edit","Salut!",
                             WS_VISIBLE | WS_CHILD |  WS_VSCROLL |
                             ES_MULTILINE ,
                             20, 500, 550, 180,hwnd,(HMENU) IDB_TEXT2, 0,NULL);
                       hSend  = CreateWindowEx(0,"Button","Send",
                             WS_CHILD | WS_VISIBLE | WS_BORDER,
                             20, 700, 550, 20,hwnd,(HMENU)Send,0,NULL);
                       hServer  = CreateWindowEx(0,"Button","Server",
                             WS_CHILD | WS_VISIBLE | WS_BORDER,
                             600, 20, 150, 20,hwnd,(HMENU)Server,0,NULL);
                       hClient  = CreateWindowEx(0,"Button","Connect To Server",
                             WS_CHILD | WS_VISIBLE | WS_BORDER,
                             600, 50, 150, 20,hwnd,(HMENU)Client,0,NULL);
                       hIp = CreateWindowEx(0,"Edit","127.0.0.1",
                             WS_CHILD | WS_VISIBLE | WS_BORDER,
                             600, 80, 150, 20,hwnd,(HMENU) Ip,
                             ((LPCREATESTRUCT)lParam)->hInstance,NULL);
    
                       SetFocus(hWin_2);
                       break;
                  case WM_COMMAND:
                       switch(wParam)
                       {
                        case Send:
                             SendData();
                             break;
                        case Server:
                             Bind_and_Listen( port );
                             cout <<"server ok\r\n";
                             EnableWindow(hServer, FALSE);
                             EnableWindow(hClient, FALSE);
                             break;
                        case Client:
                             cout <<"client ok\r\n";
                             Connect();
                             break;
                       }
                       break;
                  case WM_SERVER:
                       if(WSAGETSELECTERROR(lParam))
                       {  	// If an error occurred,
                           cout<<WSAGetLastError()<<"\r\n";
                           closesocket (sock);   WSACleanup ();		// Shutdown Winsock
                           return 0;
                       }
                       switch(WSAGETSELECTEVENT(lParam))
                       {
                        case FD_ACCEPT:
                             if ((Accept = accept(wParam, NULL, NULL)) == INVALID_SOCKET)
                             {
                                cout << "accept() failed with error " << WSAGetLastError()<<"\n";
                                break;
                             }
                             else
                             // Create a socket information structure to associate with the socket for processing I/O
                             CreateSocketInformation(Accept);
                             SendMessage(hWin_1, LB_INSERTSTRING, -1, (LPARAM)"CLIENT CONNECTED.");
                             cout << "Socket number: " << Accept << " connected\n";
    
                             WSAAsyncSelect(Accept, hwnd, WM_SERVER, FD_READ|FD_CLOSE);
                             break;
                        case FD_READ:
                             //Receive data
                             SocketInfo = GetSocketInformation(wParam);
                             i = recv(SocketInfo->Socket, recbuf1, 512, 0);
                             recbuf1[i] = '\0';
                             str1 = recbuf1;
                             itoa (wParam,name,10);
                             str2 = name; str2 += " says: "; str2 += str1;
                             SendMessage(hWin_1, LB_INSERTSTRING, -1, (LPARAM)str2.c_str());
                             cout << wParam << " says: "<< recbuf1 << "\n";
                             break;
                        case FD_CLOSE:
                             closesocket (Accept);
                             WSACleanup(); exit(1);
                             break;
                       }
                       break;
                  case WM_CLIENT:
                       if(WSAGETSELECTERROR(lParam))
                       {
                           cout<<"Socket failed with error "<< WSAGETSELECTERROR(lParam);
                           FreeSocketInformation(wParam);
                           return 0;
                       }
                       switch(WSAGETSELECTEVENT(lParam))
                       {
                        case FD_CLOSE:
                             closesocket (Accept);
                             WSACleanup(); exit(1);
                             break;
                       }
                       break;
    
                  case WM_CLOSE:
                       DestroyWindow(hwnd);
                       break;
    
                  case WM_DESTROY:
                       PostQuitMessage(0);
                       break;
                  default:
                       return DefWindowProc(hwnd,msg,wParam,lParam);
           }
           return 0;
    }
    ////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////WINMAIN/////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////////
    int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow)
    {
        WNDCLASSEX wc;
        wc.hInstance  = hInstance;
        wc.cbClsExtra = 0;
        wc.cbSize     = sizeof(WNDCLASSEX);
        wc.cbWndExtra = 0;
        wc.hbrBackground = (HBRUSH) CreateSolidBrush(RGB(100,300,100));
        wc.hCursor       = LoadCursor(NULL,IDC_ARROW);
        wc.hIcon         = LoadIcon (NULL, IDI_APPLICATION) ;
        wc.lpfnWndProc   =  WndProc;
        wc.lpszClassName = "Class";
        wc.lpszMenuName  = NULL;
        wc.style         = 0;
        wc.hIconSm       = NULL;
        if(!RegisterClassEx(&wc))
        {
            MessageBox(NULL, "Window Registration Failed!", "Error!",
            MB_ICONEXCLAMATION | MB_OK);
            return 0;
        }
    
        hwnd = CreateWindowEx(WS_EX_LEFT|WS_EX_LTRREADING|WS_EX_WINDOWEDGE,
                               "Class",
                               " The_Evil_Chatter",
                               WS_OVERLAPPEDWINDOW,
                               CW_USEDEFAULT, CW_USEDEFAULT, 900, 800,
                               HWND_DESKTOP, NULL, hInstance, NULL);
    
        if(hwnd == NULL){
           MessageBox(NULL, "Window Creation Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK); return 0;
        }
    
        ShowWindow(hwnd, nCmdShow);
        UpdateWindow(hwnd);
    
        while(GetMessage(&Msg, NULL, 0, 0) > 0)
        {
              TranslateMessage(&Msg);
              DispatchMessage(&Msg);
        }
        return Msg.wParam;
    }
    Last edited by Ducky; 01-22-2010 at 03:40 AM.
    Using Windows 10 with Code Blocks and MingW.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to do encryption in C
    By sankarv in forum C Programming
    Replies: 33
    Last Post: 12-28-2010, 11:01 AM
  2. Reading a file line by line
    By Raskalnikov in forum C Programming
    Replies: 8
    Last Post: 03-18-2009, 11:44 PM
  3. Pointer and Polymorphism help.
    By Skyy in forum C++ Programming
    Replies: 29
    Last Post: 12-18-2008, 09:17 PM
  4. Printing Length of Input and the Limited Input
    By dnguyen1022 in forum C Programming
    Replies: 33
    Last Post: 11-29-2008, 04:13 PM
  5. Finding carriage returns (\c) in a line
    By JizJizJiz in forum C++ Programming
    Replies: 37
    Last Post: 07-19-2006, 05:44 PM