Thread: Send/Recv

  1. #1
    Registered User
    Join Date
    Jul 2007
    Posts
    61

    Send/Recv

    This is what I have:
    Code:
    /*
    	Application:	Chat Client v1.0
    	By:				Brian Denys
    	Email:			[email protected]
    */
    
    /*	Include Files	*/
    #include <winsock2.h>
    #include <stdio.h>
    #pragma comment(lib, "ws2_32")
    
    #define BACKLOG 5
    
    int __cdecl Send_to_Client(const char *ip, unsigned short Port, char *Message)
    {
    	/*	Declare and Initialize variables	*/
    	int iResult;
    	WSADATA wsaData;
    	SOCKET ConnectSocket;
    	struct sockaddr_in clientConnect;
    
    	/*	Initialize Winsock	*/
    	iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    	if(iResult != NO_ERROR)
    	{
    		printf("WSAStartup() failed.\n");
    		return 1;
    	}
    
    	/*	Create socket to connect to server	*/
    	ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    	if(ConnectSocket == INVALID_SOCKET)
    	{
    		printf("Failed to create ConnectSocket.\n");
    		WSACleanup();
    		return 1;
    	}
    
    	/*	IP Address of client to send to	*/
    	clientConnect.sin_family = AF_INET;
    	clientConnect.sin_addr.s_addr = inet_addr( ip );
    	clientConnect.sin_port = htons ( Port );
    
    	/*	Connect to client	*/
    	iResult = connect(ConnectSocket, (SOCKADDR*)&clientConnect, sizeof(clientConnect));
    	if(iResult == SOCKET_ERROR)
    	{
    		printf("Failed to connect to client.\n");
    		closesocket(ConnectSocket);
    		WSACleanup();
    		return 1;
    	}
    
    	/*	Send buffer	*/
    	iResult = send(ConnectSocket, Message, (int)strlen(Message), 0);
    	if(iResult == SOCKET_ERROR)
    	{
    		printf("Failed to send buffer.\n");
    		closesocket(ConnectSocket);
    		WSACleanup();
    		return 1;
    	}else{
    		printf("Bytes send: &#37;d.", iResult);
    	}
    	
    	/*	Shutdown the connection	*/
    	iResult = shutdown(ConnectSocket, SD_SEND);
    	if(iResult == SOCKET_ERROR)
    	{
    		printf("Shutdown connection failed.\n");
    		closesocket(ConnectSocket);
    		WSACleanup();
    		return 1;
    	}
    
    	/*	Cleanup	*/
    	closesocket(ConnectSocket);
    	WSACleanup();
    
    }
    
    int __cdecl Receive_from_Client(const char *ip, unsigned short Port)
    {
    	/*	Declare and initialize variables	*/
    	int iResult;
    	WSADATA wsaData;
    	SOCKET ConnectSocket;
    	struct sockaddr_in clientRecv;
    	int recvbuflen = 512;
    	char recvbuf[512];
    
    	/*	Initialize Winsock	*/
    	iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
        if (iResult != NO_ERROR) {
          printf("WSAStartup() failed.\n");
          return 1;
        }
    
    	/*	Create a socket to connect to client	*/
    	ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (ConnectSocket == INVALID_SOCKET) {
            printf("socket() failed.\n");
            WSACleanup();
            return 1;
        }
    
    	/*	IP Address and Port of the Client to connect to	*/
    	clientRecv.sin_family = AF_INET;
        clientRecv.sin_addr.s_addr = inet_addr( ip );
        clientRecv.sin_port = htons( Port );
    
    	/*	Connect to client	*/
    	iResult = connect( ConnectSocket, (SOCKADDR*) &clientRecv, sizeof(clientRecv) );
        if ( iResult == SOCKET_ERROR) {
            closesocket (ConnectSocket);
            printf("Connect to client failed.\n");
            WSACleanup();
            return 1;
        }
    
    	/*	Receive from Client	*/
    	iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
    	printf("Received: %d\n", iResult);
    
    	/*	Shutdown the connection	*/
    	iResult = shutdown(ConnectSocket, SD_SEND);
    	if(iResult == SOCKET_ERROR)
    	{
    		printf("Shutdown connection failed.\n");
    		closesocket(ConnectSocket);
    		WSACleanup();
    		return 1;
    	}
    
    	/*	Cleanup	*/
    	closesocket(ConnectSocket);
    	WSACleanup();
    
    }
    
    int Listen_for_Client(unsigned short Port)
    {
    	/*	Declare and initialize variables	*/
    	int iResult;
    	WSADATA wsaData;
    	SOCKET ConnectSocket;
    	struct sockaddr_in clientListen;
    
    	/*	Initialize Winsock	*/
    	iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
        if (iResult != NO_ERROR) {
          printf("WSAStartup() failed.\n");
          return 1;
        }
    
    	/*	Create a socket to connect to client	*/
    	ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (ConnectSocket == INVALID_SOCKET) {
            printf("socket() failed.\n");
            WSACleanup();
            return 1;
        }
    
    	/*	IP Address and Port of the Client to connect to	*/
    	clientListen.sin_family = AF_INET;
        clientListen.sin_addr.s_addr = htonl(INADDR_ANY);
        clientListen.sin_port = htons( Port );
    
    	/*	Bind	*/
    	iResult = bind(ConnectSocket, (SOCKADDR*)&clientListen, sizeof(clientListen));
    	if(iResult == SOCKET_ERROR)
    	{
    		printf("bind() failed.\n");
    		closesocket(ConnectSocket);
    		WSACleanup();
    		return 1;
    	}
    
    	/*	Listen	*/
    	iResult = listen(ConnectSocket, BACKLOG);
    	if(iResult == SOCKET_ERROR)
    	{
    		printf("listen() failed.\n");
    		closesocket(ConnectSocket);
    		WSACleanup();
    		return 1;
    	}
    
    	printf("Listening on socket ..\n");
    
    	/*	Cleanup	*/
    	WSACleanup();
    
    }
    
    void Create1()
    {
    		Send_to_Client("127.0.0.1", 1111, "Test.");
    }
    
    void Create2()
    {
    	Receive_from_Client("127.0.0.1", 1111);
    }
    
    void Create3()
    {
    	Listen_for_Client(1111);
    }
    
    int __cdecl main()
    {
    	CreateThread(NULL, 0, (unsigned long(__stdcall*)(void*))Create3, NULL, 0, NULL);
    	CreateThread(NULL, 0, (unsigned long(__stdcall*)(void*))Create2, NULL, 0, NULL);
    	CreateThread(NULL, 0, (unsigned long(__stdcall*)(void*))Create1, NULL, 0, NULL);
    
    	system("pause");
    	return 0;
    }
    I don't receive the msg i just send, why?
    Last edited by brietje698; 12-12-2007 at 12:26 PM.

  2. #2
    Registered User
    Join Date
    Jul 2007
    Posts
    61
    Code:
    /*
    	Application:	Chat Client v1.0
    	By:				Brian Denys
    	Email:			[email protected]
    */
    
    /*	Include Files	*/
    #include <winsock2.h>
    #include <stdio.h>
    #pragma comment(lib, "ws2_32")
    
    #define BACKLOG 5
    
    int __cdecl Send_to_Client(const char *ip, unsigned short Port, char *Message)
    {
    	/*	Declare and Initialize variables	*/
    	int iResult;
    	WSADATA wsaData;
    	SOCKET ConnectSocket;
    	struct sockaddr_in clientConnect;
    
    	/*	Initialize Winsock	*/
    	iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    	if(iResult != NO_ERROR)
    	{
    		printf("WSAStartup() failed.\n");
    		return 1;
    	}
    
    	/*	Create socket to connect to server	*/
    	ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    	if(ConnectSocket == INVALID_SOCKET)
    	{
    		printf("Failed to create ConnectSocket.\n");
    		WSACleanup();
    		return 1;
    	}
    
    	/*	IP Address of client to send to	*/
    	clientConnect.sin_family = AF_INET;
    	clientConnect.sin_addr.s_addr = inet_addr( ip );
    	clientConnect.sin_port = htons ( Port );
    
    	/*	Connect to client	*/
    	iResult = connect(ConnectSocket, (SOCKADDR*)&clientConnect, sizeof(clientConnect));
    	if(iResult == SOCKET_ERROR)
    	{
    		printf("Failed to connect to client.\n");
    		closesocket(ConnectSocket);
    		WSACleanup();
    		return 1;
    	}
    
    	/*	Send buffer	*/
    	iResult = send(ConnectSocket, Message, (int)strlen(Message), 0);
    	if(iResult == SOCKET_ERROR)
    	{
    		printf("Failed to send buffer.\n");
    		closesocket(ConnectSocket);
    		WSACleanup();
    		return 1;
    	}else{
    		printf("Message send: %s.", Message);
    	}
    	
    	/*	Shutdown the connection	*/
    	iResult = shutdown(ConnectSocket, SD_SEND);
    	if(iResult == SOCKET_ERROR)
    	{
    		printf("Shutdown connection failed.\n");
    		closesocket(ConnectSocket);
    		WSACleanup();
    		return 1;
    	}
    
    	/*	Cleanup	*/
    	closesocket(ConnectSocket);
    	WSACleanup();
    
    }
    
    int Listen_for_Client(unsigned short Port)
    {
    	/*	Declare and initialize variables	*/
    	int iResult2;
    	WSADATA wsaData2;
    	SOCKET ConnectSocket2;
    	SOCKET AcceptSocket;
    	struct sockaddr_in clientListen;
    	int recvbuflen = 512;
    	char recvbuf[512];
    
    	/*	Initialize Winsock	*/
    	iResult2 = WSAStartup(MAKEWORD(2,2), &wsaData2);
        if (iResult2 != NO_ERROR) {
          printf("WSAStartup() failed.\n");
          return 1;
        }
    
    	/*	Create a socket to connect to client	*/
    	ConnectSocket2 = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (ConnectSocket2 == INVALID_SOCKET) {
            printf("socket() failed.\n");
            WSACleanup();
            return 1;
        }
    
    	/*	IP Address and Port of the Client to connect to	*/
    	clientListen.sin_family = AF_INET;
        clientListen.sin_addr.s_addr = htonl(INADDR_ANY);
        clientListen.sin_port = htons( Port );
    
    	/*	Bind	*/
    	iResult2 = bind(ConnectSocket2, (SOCKADDR*)&clientListen, sizeof(clientListen));
    	if(iResult2 == SOCKET_ERROR)
    	{
    		printf("bind() failed.\n");
    		closesocket(ConnectSocket2);
    		WSACleanup();
    		return 1;
    	}
    
    	/*	Listen	*/
    	iResult2 = listen(ConnectSocket2, BACKLOG);
    	if(iResult2 == SOCKET_ERROR)
    	{
    		printf("listen() failed.\n");
    		closesocket(ConnectSocket2);
    		WSACleanup();
    		return 1;
    	}
    
    	printf("Listening on socket ..\n");
    
    	/*	Accept	*/
    	while(true){
    	AcceptSocket = accept(ConnectSocket2, NULL, NULL);
    	if (AcceptSocket == INVALID_SOCKET)
    	{
    		printf("accept() failed\n");
    		closesocket(ConnectSocket2);
    		WSACleanup();
    		return 1;
    	}else{
    		printf("Client connected.\n");
    		iResult2 = recv(AcceptSocket, recvbuf, recvbuflen, 0);
            printf("Message received: %s\n", &recvbuf);
    	}
    	}
    
    	/*	Cleanup	*/
    	closesocket(ConnectSocket2);
    	WSACleanup();
    
    }
    
    void Create2()
    {
    	char *Msg = "omg";
    		Send_to_Client("127.0.0.1", 1111, Msg);
    }
    
    void Create1()
    {
    	Listen_for_Client(1111);
    }
    
    int __cdecl main()
    {
    	CreateThread(NULL, 0, (unsigned long(__stdcall*)(void*))Create1, NULL, 0, NULL);
    	CreateThread(NULL, 0, (unsigned long(__stdcall*)(void*))Create2, NULL, 0, NULL);
    
    	system("pause");
    	return 0;
    }
    Why I am getting a buch of strange characters in my receive?

  3. #3
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    you do not send the null termination.
    So obviously - you do not receive it

    Or - while printing add preceision to your format to print exactly the same number of chars you have received

    Or add the null terminator manually - after the last received character before printing (check for memory overrun in this solution)
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  4. #4
    Registered User
    Join Date
    Jul 2007
    Posts
    61
    Thanks got that working =]
    Now i still have to make a chat client from that =]
    Last edited by brietje698; 12-13-2007 at 07:44 AM.

  5. #5
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    If you want to process several connections - maybe better to start work asynchrony on the select
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  6. #6
    Registered User
    Join Date
    Jul 2007
    Posts
    61
    Whats wrong with:

    Code:
    char *Msg;
    cin >> Msg;
    printf(Msg);
    I'm using VC2008

  7. #7
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Do you mean aside from you not allocating any memory for Msg?

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  8. #8
    Registered User
    Join Date
    Jul 2007
    Posts
    61
    Quote Originally Posted by matsp View Post
    Do you mean aside from you not allocating any memory for Msg?

    --
    Mats
    Unhandled exception at 0x104e63b1 in Chat.exe: 0xC0000005: Access violation writing location 0xcccccccc.

  9. #9
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by brietje698 View Post
    Unhandled exception at 0x104e63b1 in Chat.exe: 0xC0000005: Access violation writing location 0xcccccccc.
    Yes, let me guess that "Msg" happens to be 0xcccccccc when you do this? Have you tried actually single-stepping into the function, rather than asking here? Do you understand how cin and printf() uses memory?

    You have not set Msg to a valid memory location to write to, and since Visual Studio ensures that uninitialized variables are still set to a defined value, you get this, rather than just randomly overwriting something in your memory - much better, I think.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  10. #10
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    Quote Originally Posted by brietje698 View Post
    Whats wrong with:

    Code:
    char *Msg;
    cin >> Msg;
    printf(Msg);
    The first parameter of printf treats % as special, so you'd have to do it like this:
    Code:
    char *Msg;
    cin >> Msg;
    printf("%s",Msg);

  11. #11
    Registered User
    Join Date
    Jul 2007
    Posts
    61
    Quote Originally Posted by robwhit View Post
    The first parameter of printf treats % as special, so you'd have to do it like this:
    Code:
    char *Msg;
    cin >> Msg;
    printf("%s",Msg);
    it the line
    Code:
    cin >> Msg;
    thats givng me the error

  12. #12
    Captain - Lover of the C
    Join Date
    May 2005
    Posts
    341
    That's because Msg points to one byte (assuming char is 1 byte) of memory. You are assuming it is pointing to a chunk of memory big enough to hold whatever is inputted. The program may or may not crash depending on who or what owns the memory directly after the 1 byte pointed to by Msg. If you want to make sure that you have a chunk of memory you need to ALLOCATE it.

    in C:
    Code:
    Msg = malloc(sizeof(char) * HoweverManyCharactersYouExpect);
    in C++
    Code:
    Msg = new char[HoweverManyCharacterYouExpect];
    Don't quote me on that... ...seriously

  13. #13
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    Msg isn't allocalted any memory. Make it an array or dynamically allocate it.

  14. #14
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    You can't allocate memory and you are writing a socket program?? Hmmm.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. non-blocking send/recv
    By antex in forum Networking/Device Communication
    Replies: 14
    Last Post: 05-31-2007, 01:10 PM
  2. help with socket send/recv
    By ac251404 in forum Networking/Device Communication
    Replies: 10
    Last Post: 06-29-2006, 07:32 PM
  3. send/recv binary files using sockets in C++
    By dafatdude in forum Networking/Device Communication
    Replies: 14
    Last Post: 07-25-2004, 11:00 AM
  4. How to make a thread sleep or std::recv timeout?
    By BrianK in forum Linux Programming
    Replies: 3
    Last Post: 02-26-2003, 10:27 PM