9 Replies - 5089 Views - Last Post: 04 October 2011 - 09:08 PM

#1 ToKii  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 31-March 11

[HELP] C++ Chat Program

Posted 31 March 2011 - 01:59 PM

Hello all ToKii here,

I am having to create a chat program in Windows express 2008 and I have a separate server and client code as followed:

Client Code:

#include "stdafx.h"
#include "Form1.h"
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <windows.h>
#include <iostream>
#include <string>



static DWORD WINAPI client(LPVOID pram);


struct addrinfo *result = NULL,
                *ptr = NULL,
                hints;
#define DEFAULT_PORT "27015"
#define DEFAULT_BUFLEN 512

using namespace Tokii;

[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
	// Enabling Windows XP visual effects before any controls are created
	Application::EnableVisualStyles();
	Application::SetCompatibleTextRenderingDefault(false); 

	// Create the main window and run it
	Application::Run(gcnew Form1());
	HANDLE  hThread2;

	hThread2 = CreateThread(NULL,0,client,NULL,0,NULL);

	char ans = 'n';
	std::cout<<"\nHit q to quit\n";
	std::cin>>ans;
	while(true){}

	return 0;
}


DWORD WINAPI client(LPVOID pram){
	int iResult = 0;
	WSADATA wsaData;

	// Initialize Winsock
	iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
	if (iResult != 0) {
		printf("WSAStartup failed: %d\n", iResult);
		return 1;
	}

	ZeroMemory( &hints, sizeof(hints) );
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;

	iResult = getaddrinfo("10.17.1.165", DEFAULT_PORT, &hints, &result);
	if ( iResult != 0 ) {
		printf("getaddrinfo failed: %d\n", iResult);
		WSACleanup();
		return 1;
	}

	SOCKET ConnectSocket = INVALID_SOCKET;
	// Attempt to connect to the first address returned by
	// the call to getaddrinfo
	ptr=result;

	// Create a SOCKET for connecting to server
	ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,ptr->ai_protocol);
	if (ConnectSocket == INVALID_SOCKET) {
		printf("Error at socket(): %ld\n", WSAGetLastError());
		freeaddrinfo(result);
		WSACleanup();
		return 1;
	}
	// Connect to server.
	iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
	if (iResult == SOCKET_ERROR) {
		closesocket(ConnectSocket);
		ConnectSocket = INVALID_SOCKET;
	}

	// Should really try the next address returned by getaddrinfo
	// if the connect call failed
	// But for this simple example we just free the resources
	// returned by getaddrinfo and print an error message

	freeaddrinfo(result);

	if (ConnectSocket == INVALID_SOCKET) {
		printf("Unable to connect to server!\n");
		WSACleanup();
		return 1;
	}

	int recvbuflen = DEFAULT_BUFLEN;

	//char *sendbuf = "this is a test";
	char recvbuf[DEFAULT_BUFLEN];

	// Send an initial buffer
	std::cout<<"Message to send?\n";
	std::string temp;
	getline(std::cin,temp);
	const char *sendbuf;
	sendbuf = temp.c_str();
	std::cout<<"Sending "<<sendbuf<<"\n";

	iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
	if (iResult == SOCKET_ERROR) {
		printf("send failed: %d\n", WSAGetLastError());
		closesocket(ConnectSocket);
		WSACleanup();
		return 1;
	}

	printf("Bytes Sent: %ld\n", iResult);

	// shutdown the connection for sending since no more data will be sent
	// the client can still use the ConnectSocket for receiving data
	iResult = shutdown(ConnectSocket, SD_SEND);
	if (iResult == SOCKET_ERROR) {
		printf("shutdown failed: %d\n", WSAGetLastError());
		closesocket(ConnectSocket);
		WSACleanup();
		return 1;
	}

	// Receive data until the server closes the connection
	do {

		iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
		std::cout<<"Client: received "<<recvbuf<<"\n";
		if ( iResult > 0 )
			printf("Bytes received: %d\n", iResult);
		else if ( iResult == 0 )
			printf("Connection closed\n");
		else
			printf("recv failed: %d\n", WSAGetLastError());

	} while( iResult > 0 );

	// shutdown the send half of the connection since no more data will be sent
	iResult = shutdown(ConnectSocket, SD_SEND);
	if (iResult == SOCKET_ERROR) {
		printf("shutdown failed: %d\n", WSAGetLastError());
		closesocket(ConnectSocket);
		WSACleanup();
		return 1;
	}

	// cleanup
	closesocket(ConnectSocket);
	WSACleanup();

	return 0;
}




Server Code:

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <stdio.h>

#pragma comment(lib, "Ws2_32.lib")

int main() {
	WSADATA wsaData;
int iResult;

// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
    printf("WSAStartup failed: %d\n", iResult);
    return 1;
}
#define DEFAULT_PORT "27015"

struct addrinfo *result = NULL, *ptr = NULL, hints;

ZeroMemory(&hints, sizeof (hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;

// Resolve the local address and port to be used by the server
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
    printf("getaddrinfo failed: %d\n", iResult);
    WSACleanup();
    return 1;
}
SOCKET ListenSocket = INVALID_SOCKET;

// Create a SOCKET for the server to listen for client connections
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);


if (ListenSocket == INVALID_SOCKET) {
    printf("Error at socket(): %ld\n", WSAGetLastError());
    freeaddrinfo(result);
    WSACleanup();
    return 1;
}

   // Setup the TCP listening socket
    iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
        printf("bind failed with error: %d\n", WSAGetLastError());
        freeaddrinfo(result);
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

 freeaddrinfo(result);
if ( listen( ListenSocket, SOMAXCONN ) == SOCKET_ERROR ) {
    printf( "Listen failed with error: %ld\n", WSAGetLastError() );
    closesocket(ListenSocket);
    WSACleanup();
    return 1;
}


SOCKET ClientSocket;


ClientSocket = INVALID_SOCKET;

// Accept a client socket
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
    printf("accept failed: %d\n", WSAGetLastError());
    closesocket(ListenSocket);
    WSACleanup();
    return 1;
}
ClientSocket = INVALID_SOCKET;

// Accept a client socket
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
    printf("accept failed: %d\n", WSAGetLastError());
    closesocket(ListenSocket);
    WSACleanup();
    return 1;
}
#define DEFAULT_BUFLEN 512

char recvbuf[DEFAULT_BUFLEN];
int iSendResult;
int recvbuflen = DEFAULT_BUFLEN;

// Receive until the peer shuts down the connection
do {

    iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
    if (iResult > 0) {
        printf("Bytes received: %d\n", iResult);

        // Echo the buffer back to the sender
        iSendResult = send(ClientSocket, recvbuf, iResult, 0);
        if (iSendResult == SOCKET_ERROR) {
            printf("send failed: %d\n", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();
            return 1;
        }
        printf("Bytes sent: %d\n", iSendResult);
    } else if (iResult == 0)
        printf("Connection closing...\n");
    else {
        printf("recv failed: %d\n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return 1;
    }

} while (iResult > 0);

// shutdown the send half of the connection since no more data will be sent
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
    printf("shutdown failed: %d\n", WSAGetLastError());
    closesocket(ClientSocket);
    WSACleanup();
    return 1;
}

// cleanup
closesocket(ClientSocket);
WSACleanup();

return 0;

}



Now, this code works through the command prompt, but I would:

1. Like to incoporate this code into a Windows Forms Application for nicer looks (client)

2. Have the server code be able to multi-thread so I am able to have infinite sockets so anyone who has this client can connect to it.

Thankyou for all future help!

Sincerely,

ToKii

Is This A Good Question/Topic? 0
  • +

Replies To: [HELP] C++ Chat Program

#2 Macjohn  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 80
  • View blog
  • Posts: 407
  • Joined: 10-April 09

Re: [HELP] C++ Chat Program

Posted 31 March 2011 - 03:24 PM

To say the truth I've never used c++ with windows for but I'm pretty sure that you will find some help here in this 2 links below.

msdn c++ forms1

msdn c++ forms2
Was This Post Helpful? 1
  • +
  • -

#3 ToKii  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 31-March 11

Re: [HELP] C++ Chat Program

Posted 31 March 2011 - 03:50 PM

thankyou for your response. I will look into these links.

EDIT: Thankyou for the information but I have already read all that and it does not cover what I need.

This post has been edited by ToKii: 31 March 2011 - 03:51 PM

Was This Post Helpful? 0
  • +
  • -

#4 Macjohn  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 80
  • View blog
  • Posts: 407
  • Joined: 10-April 09

Re: [HELP] C++ Chat Program

Posted 31 March 2011 - 03:57 PM

Sorry, but I didn't quite understand...in your client project you cant insert a windows form?

When you go to new project in c++ and then CLR there you can choose your windows forms app...

Either that or i didn't understand nothing...

This post has been edited by Macjohn: 31 March 2011 - 04:06 PM

Was This Post Helpful? 0
  • +
  • -

#5 ToKii  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 31-March 11

Re: [HELP] C++ Chat Program

Posted 01 April 2011 - 08:17 AM

I understand that but my code seems to not work in the original.cpp file or a custom header file with the same error of not working with clr/:safe or clr/:pure....
Was This Post Helpful? 0
  • +
  • -

#6 ToKii  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 31-March 11

Re: [HELP] C++ Chat Program

Posted 11 April 2011 - 08:16 AM

Anyone? I could use some help here... :whistling:
Was This Post Helpful? 0
  • +
  • -

#7 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6078
  • View blog
  • Posts: 23,548
  • Joined: 23-August 08

Re: [HELP] C++ Chat Program

Posted 11 April 2011 - 10:11 AM

Moved to CLI C++
Was This Post Helpful? 0
  • +
  • -

#8 ToKii  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 31-March 11

Re: [HELP] C++ Chat Program

Posted 11 April 2011 - 10:14 AM

i have to do it in windows forms application or I would.
Was This Post Helpful? 0
  • +
  • -

#9 ToKii  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 31-March 11

Re: [HELP] C++ Chat Program

Posted 12 April 2011 - 01:26 PM

Thankyou for moving it to the correct place. I need the Server code to be able to either use an array to have sockets for the clients for multithread for them.
Was This Post Helpful? 0
  • +
  • -

#10 shammancer  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 110
  • Joined: 03-September 10

Re: [HELP] C++ Chat Program

Posted 04 October 2011 - 09:08 PM

A good place to look into multi threading is openmp.org check IF visual express 2008 can compile the code.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1