Important alert: (current site time 4/24/2014 4:19:39 AM EDT)
 

VB icon

Alternating Winsock Chat

Email
Submitted on: 11/25/2002 9:57:21 PM
By: Phillip Hopkins  
Level: Intermediate
User Rating: By 8 Users
Compatibility: Microsoft Visual C++
Views: 20472
(About the author)
 
     This code is just a little beginning project of mine that I wrote when I first began learning to use winsock. Because this was my first practical application of my winsock knowledge, it is not quite so sophisticated, and it is thusly an ALTERNATING chat program. . . sorry. . .anyway, even though I wrote this code about 2 years ago, and it is useless to me now, I thought I would post it for those who may wish to learn winsock and need a good example. I tried my best to comment it, but I am really not used to using many comments in my codes, so bear with me. If you need any explanations, mail me.

 

INCLUDE files:

Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
//**************************************
//INCLUDE files for :Alternating Winsock Chat
//**************************************
iostream.h
winsock.h
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
 
Terms of Agreement:   
By using this code, you agree to the following terms...   
  1. You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this code (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this code from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the code or code's description.
				
//**************************************
// Name: Alternating Winsock Chat
// Description:This code is just a little beginning project of mine that I wrote when I first began learning to use winsock. Because this was my first practical application of my winsock knowledge, it is not quite so sophisticated, and it is thusly an ALTERNATING chat program. . . sorry. . .anyway, even though I wrote this code about 2 years ago, and it is useless to me now, I thought I would post it for those who may wish to learn winsock and need a good example. I tried my best to comment it, but I am really not used to using many comments in my codes, so bear with me. If you need any explanations, mail me.
// By: Phillip Hopkins
//
// Assumes:you MUST add the "mpr.lib" and "wsock32.lib" libraries to you project in order to compile this. If you need detailed instructions on how to do this, E-mail me and I can help.
//
//This code is copyrighted and has// limited warranties.Please see http://www.Planet-Source-Code.com/vb/scripts/ShowCode.asp?txtCodeId=5279&lngWId=3//for details.//**************************************

// Created by Phillip D. Hopkins
// of Philware Inc.
// sites
// www.philwareinc.com (soon to be launched)
// www.philwareinc.20m.com (already up)
#include <iostream.h>
#include <winsock.h>
void ClearScreen();	//A VERY cheap and fake "Clear Screen" function
int DisplayMenu()	//A simple function to display the menu and get the response
{
	int choice;
beginning:
	ClearScreen();
	cout << endl << endl << endl << endl << endl << endl << endl << "Philware WINSOCK Test V1.0" << endl;
	cout << "Choose the correct Connection Type:" << endl;
	cout << "1. Server" << endl;
	cout << "2. Client" << endl;
	cout << "3. Exit" << endl;
	cout << "Choice: ";
	cin >> choice;
	if (choice != 1 && choice != 2 && choice != 3)
	{
		cout << "That is not one of the choices." << endl;
		goto beginning;
	}
	return choice;
}
int main()
{
	WSADATA WsaDat;				//Declares what is necessary to use winsock
	int menuchoice;				//Gets the integer from the "DisplayMenu()" function
	if (WSAStartup(MAKEWORD(1,1), &WsaDat) != 0)	//Initiallizes the WSA
	{
		cout << "WSA initialization failed.";
		cout << "Closing. . .";
		Sleep(MAKEWORD(10,30));
		goto end;
	}
	SOCKET mysocket;			//Our Handy Dandy Socket
	mysocket = socket(AF_INET, SOCK_STREAM, 0);		//Sets the properties of our socket
													//Here, it is set to a STREAM Socket
	
	if (mysocket == INVALID_SOCKET)					//Checks to see if it created correctly
	{
		cout << "Socket creation failed!";
		cout << "Closing. . .";
		Sleep(MAKEWORD(10,30));
		goto end;
	}
	int ip1, ip2, ip3, ip4, yesno;					//Holders for IP address, and a
													//"yesno" var for confirmation later
reipadd:	//Yah, I know it is bad, but I did use a nasty "goto" command
	cout << "\nChoose your IP address:\n";			//It has you enter the server's
	cout << "first numeral: ";						//IP address one numeral at a time
	cin >> ip1;
	cout << "second numeral:";
	cin >> ip2;
	cout << "third numeral: ";
	cin >> ip3;
	cout << "fourth numeral:";
	cin >> ip4;
	cout << "\nIs this your IP address? (1=yes, 2=no)\n" << ip1 << "." << ip2 << "." << ip3 << "." << ip4 << endl;
	cin >> yesno;				//this just shows the ip and ask for verification
	if (yesno!=1)
	{
		goto reipadd;			//here is that nasty "goto" command. . .
	}
	SOCKADDR_IN SockAddr;		//this keeps track of the socket's address info
	SockAddr.sin_port = 50;
	SockAddr.sin_family = AF_INET;
	SockAddr.sin_addr.S_un.S_un_b.s_b1 = ip1;
	SockAddr.sin_addr.S_un.S_un_b.s_b2 = ip2;
	SockAddr.sin_addr.S_un.S_un_b.s_b3 = ip3;
	SockAddr.sin_addr.S_un.S_un_b.s_b4 = ip4;
	char myscreenname[20], theirscreenname[20];	// self-explanatory :)
rescreenname:	//another reference to that "goto" command
	//lets you enter a screen name
	cout << endl << "Type in a one-word \"Screen Name\" less than 20 letters" << endl;
	cin.ignore(80, '\n');
	cin.get(myscreenname, 20);
	cin.ignore(80, '\n');
	//checks to see if you typed it right
	cout << "Your screen name is :" << myscreenname << endl << "Do you want this screen name?(1=yes 2=no)" << endl;
	cin >> yesno;
	if (yesno!=1)
	{
		goto rescreenname; //yup, this will have you retype the screen name
	}
	
	
	menuchoice=DisplayMenu();	//shows the menu and gets a choice (defined at top of code)
	
	if (menuchoice==1)			// if you chose to be a server. . . 
	{
								// bind to IP address. . .
		if (bind(mysocket, (SOCKADDR *)(&SockAddr), sizeof(SockAddr)) == SOCKET_ERROR)
		{
			cout << "Attempt to bind failed" << endl;
			cout << "Closing. . .";
			Sleep(MAKEWORD(10,30));
			goto end;
		}
		
		cout << "Waiting for client. . ." << endl;
								//go into "Listen" mode. . .
		listen(mysocket, 1);
								//when request received to connect, accept it
		SOCKET TempSock = SOCKET_ERROR;
		while (TempSock == SOCKET_ERROR)
		{
			TempSock = accept(mysocket, NULL, NULL);
		}
		mysocket = TempSock;
								//send your screen name to the client
		cout << "Client Found. Sending screen name. . ." << endl;
		send(mysocket, myscreenname, sizeof(myscreenname), 0);
		cout << "Screen name sent successfully." << endl;
		cout << "Retrieving screen name from client. . ." << endl;
								//wait to receive screen name from client
		int WaitforScreenName = SOCKET_ERROR;
		while (WaitforScreenName == SOCKET_ERROR)
		{
			WaitforScreenName = recv(mysocket, theirscreenname, 20, 0);
			if ((WaitforScreenName == 0)||(WaitforScreenName == WSAECONNRESET))
			{
				cout << "Connection closed at the other end while receiving screen name! RATS!" << endl;
				cout << "Closing. . .";
				Sleep(MAKEWORD(10,30));
				goto end;
			}
		cout << "Screen Name Acquired. You are talking with: " << theirscreenname << endl;
		}
		
		char toclient[50], String2[50];
		int RetVal = SOCKET_ERROR;
send1:							//type and send message to client
		cout << myscreenname << ": ";
		cin.ignore(80, '\n');
		cin.get(toclient, 50);
		cin.ignore(80, '\n');
		send(mysocket, toclient, 50, 0);
//		cout << "MESSAGE SENT" << endl << "Waiting for reply. . ." << endl;
								//wait for the client to send a message. . .
		while (RetVal == SOCKET_ERROR)
		{
			RetVal = recv(mysocket, String2, 50, 0);
			if ((RetVal == 0)||(RetVal == WSAECONNRESET))
			{
				cout << "Connection closed at the other end. . .Sorry. . ." << endl;
				cout << "Closing. . .";
				Sleep(MAKEWORD(10,30));
				goto end;
			}
								//display message
//			cout << "Message Received:" << endl;
			cout << theirscreenname << ": " << String2 << endl;
			RetVal = SOCKET_ERROR;
			goto send1;			// loop and send another message
		}
		
//		cout << "\nThis message was sent:" << endl;
//		cout << "THIS IS FROM THE SERVER, TEST SUCCESSFUL";
//		int pause;
//		cin >> pause;
	}
	else if (menuchoice==2)
	{
								//attempt to connect to server. . .
		cout << "Trying to connect to a server. . ." << endl;
		if (connect(mysocket, (SOCKADDR *)(&SockAddr), sizeof(SockAddr)) == SOCKET_ERROR)
		{
			cout << "failed to establish connection with server" << endl;
			cout << "Closing. . .";
			Sleep(MAKEWORD(10,30));
			goto end;
		}
								//wait to receive screen name
		cout << "Server Found! Waiting to receive Screen Name. . ." << endl;
		int WaitforScreenName = SOCKET_ERROR;
		while (WaitforScreenName == SOCKET_ERROR)
		{
			WaitforScreenName = recv(mysocket, theirscreenname, 20, 0);
			if ((WaitforScreenName == 0)||(WaitforScreenName == WSAECONNRESET))
			{
				cout << "Connection closed at the other end while receiving screen name!" << endl;
				cout << "Closing. . .";
				Sleep(MAKEWORD(10,30));
				goto end;
			}
		cout << "Screen Name Acquired. You are talking with: " << theirscreenname << endl;
		
								//send screen name to server
		cout << "Sending your screen name. . ." << endl;
		send(mysocket, myscreenname, sizeof(myscreenname), 0);
		cout << "Screen Name Sent!" << endl;
		
								//wait for message from server
		cout << "Waiting for first Message from " << theirscreenname << ". . ." << endl;
		}
		int RetVal = SOCKET_ERROR;
		char String[50], toserver[50];
send2:
		while (RetVal == SOCKET_ERROR)
		{
			RetVal = recv(mysocket, String, 50, 0);
			if ((RetVal == 0)||(RetVal == WSAECONNRESET))
			{
				cout << "Connection closed at the other end" << endl;
				cout << "Closing. . .";
				Sleep(MAKEWORD(10,30));
				goto end;
			}
			
//			cout << "Message Received:" << endl;
			cout << theirscreenname << ": " << String << endl;
//			int pause1;
//			cout << "\nThis message was received:" << endl;
//			cout << String;
//			cin >> pause1;
		}
		
								//type and send message to server
		cout << myscreenname << ": ";
		cin.ignore(80, '\n');
		cin.get(toserver, 50);
		cin.ignore(80, '\n');
//		cout << "Sending message. . ." << endl;
		send(mysocket, toserver, 50, 0);
//		cout << "Message Sent. Waiting for reply from " << theirscreenname << ". . ." << endl;
		RetVal = SOCKET_ERROR;
		goto send2;				//loop back and wait for another message
	}
	else if (menuchoice==3)
	{
								//close the program
		cout << "Closing. . .";
		Sleep(MAKEWORD(10,30));
		goto end;
	}
		
end:
	return 0;
}
void ClearScreen()				//Here be the cheesy "Screen Clear" function
{
	cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
}


Other 1 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Intermediate category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments

11/26/2002 10:29:30 AMJose M Serrano

It's a good program, I'm learning Winsock programming, and I think it's really useful. 5 votes
(If this comment was disrespectful, please report it.)

 
11/27/2002 11:25:15 PM

yo phil *cough* lame *cough* lol jk nice
(If this comment was disrespectful, please report it.)

 
12/29/2002 8:37:50 AM

Error in Makeword command! :(
if (WSAStartup(MAKEWORD(1,1), &WsaDat) != 0) //Initiallizes the WSA
(If this comment was disrespectful, please report it.)

 
12/29/2002 12:17:29 PMPhillip Hopkins

There is an Error in the MAKEWORD macro? I am sorry, but I fail to see the problem. . . I have compiled this exact code just fine on my own. . . Did you include the libraries "mpr.lib" and "wsock32.lib" into your project? if that is not the problem, please elaborate so that I may find a solution.
(If this comment was disrespectful, please report it.)

 
1/7/2003 6:17:26 PM

I have not test it, however I truly appreciated that you took the time and effort to share this with us. Thank you.
(If this comment was disrespectful, please report it.)

 
2/9/2003 4:16:54 AMbahruddina

great code, thanx for sharing ur knowledge . 5 from me
(If this comment was disrespectful, please report it.)

 
4/22/2003 8:02:20 AM

If, for whatever reason, you can't get the MAKEWORD(x,y) macro working (which should be defined in windows.h), try this (placed at the top of the program, or, even better, in a user-defined header file):

#define MAKEWORD(x,y) x+y*0x0100
(If this comment was disrespectful, please report it.)

 
4/22/2003 8:03:19 AM

Err, the #define and the x+y*0x0100 all on one line
(If this comment was disrespectful, please report it.)

 
5/22/2003 9:57:17 PMDilshan Jesook

Nice peice of tutorial, i guess the next step would be to make it work with threads. :-)
(If this comment was disrespectful, please report it.)

 
6/23/2003 4:21:38 PMBobby S

Thanks for sharing this with us.

How do you add the libraries?
(If this comment was disrespectful, please report it.)

 
7/1/2003 8:10:02 PMPhillip Hopkins

All you have to do is go under your Project Settings, find the Link tab, and add the names of the libraries to the Object/Library Modules box.
(If this comment was disrespectful, please report it.)

 
7/6/2003 11:32:29 PMWolf McCloud

or right-click your file view, and add file: WS2_32.LIB
(If this comment was disrespectful, please report it.)

 
7/6/2003 11:35:53 PMWolf McCloud

To clear the screen you can use  system("cls");
(If this comment was disrespectful, please report it.)

 
7/11/2003 11:05:49 PM

I get an error
(If this comment was disrespectful, please report it.)

 
7/11/2003 11:06:48 PM

i get an error UNRESoLVED EXTERNAL SYMBOL. I get this on other winsock apps. Any ideas?
(If this comment was disrespectful, please report it.)

 
7/13/2003 5:26:52 PMPhillip Hopkins

Simple. I have to answer this question all the time, so I am posting it now to prevent all further questions. Please note the ASSUMES part of the comment at the top of the code. Just add the 2 libraries mpr.lib and wsock32.lib to your project and you shouldn't get those Unresolved External Symbol errors.
(If this comment was disrespectful, please report it.)

 
7/20/2003 2:07:38 PMWolf McCloud

Since you know how to get Winsock to work, why don't you write a small tutorial on how to use it using v2.0 or something newer than v1.0. It would help out tons of programmers and if your tutorial is well explained and works, you might win an award because Winsock is one of the hardest things in C++... after string manipulation outside dos apps.
(If this comment was disrespectful, please report it.)

 
7/20/2003 4:16:46 PMWolf McCloud

If you dont, I will. :-P
(If this comment was disrespectful, please report it.)

 
7/21/2003 3:32:54 PMPhillip Hopkins

A tutorial, eh? Well, to be quite honest, I haven't used more than Winsock V 1.1 in my programs to date, but if the C++ Community needs a Winsock 2.0 tutorial, I'd be happy to make the contribution. The program on display here was written during my second year of studying C++, so it is relatively primitive. I'll certainly take this request into consideration; and, seeing as I am a competitive spirit, I will see if I can't beat you to it, Wolf McCloud! :-)
(If this comment was disrespectful, please report it.)

 
1/1/2004 11:04:13 AM

hello, nice coding but after sending 1 msg the server doesn't respond anymore :S any suggestions?
(If this comment was disrespectful, please report it.)

 
1/2/2004 1:18:11 AMPhillip Hopkins

Ha ha, yeah. . . That's why its called an Alternating winsock chat. . . if you look closely at the code, you'll notice that it sends a message, and then waits for a message. I know that is incredibly strange, but remember, this was my first attempt at using Winsock, and I posted it simply because it showed the basics of how to use Winsock. If you want an asynchronous connection, the code is much different, and to my knowledge it can't be done in a DOS app. . . but correct me if I am wrong!
(If this comment was disrespectful, please report it.)

 
1/14/2004 4:08:26 PMJames

Great Work! This helped me out alot!
(If this comment was disrespectful, please report it.)

 
4/2/2004 1:40:04 AM

What's going on with my code?? look what I am getting...kaoz error LNK2019: unresolved external symbol _recv@16 referenced in function _main





kaoz error LNK2019: unresolved external symbol _send@16 referenced in function _main



kaoz error LNK2019: unresolved external symbol _socket@12 referenced in function _main


can anyone help?


(If this comment was disrespectful, please report it.)

 
4/4/2004 12:18:17 AMPhillip Hopkins

Simple. When you get 'unresolved external symbol' errors, it means you have not included mpr.lib and wsock32.lib in your project for the build. I think I mentioned that earlier though. . . check through some of the other comments.
(If this comment was disrespectful, please report it.)

 
8/27/2004 5:14:36 PM

it gives me this error when i try to compile:
warning: initialization of negative value `-1' to `SOCKET'
(If this comment was disrespectful, please report it.)

 
8/27/2004 9:15:00 PMPhillip Hopkins

That's just a warning, though, right? Is it not allowing you to compile?
(If this comment was disrespectful, please report it.)

 
3/30/2006 11:52:17 PMTrix

Please tell me how to use winscok in c++ Because i dont understand your program when I try your program many occored there is no library in winsock.h. It needs to install or what?
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)
 

To post feedback, first please login.