Click here to Skip to main content
11,718,289 members (83,469 online)
Click here to Skip to main content
Add your own
alternative version

Server Client Sockets

, 25 Apr 2003 355.8K 11.9K 182
Sample application Uses Server and client socket to establish exchange of data
#include <windows.h>
#include <winsock.h>
#include <iostream>

using namespace std;

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

#define CS_ERROR 1
#define CS_OK 0

void sError(char*);

int main()
{

	WORD version;
	WSADATA wsaData;
	int rVal=0;

	version = MAKEWORD(1,1);

	WSAStartup(version,(LPWSADATA)&wsaData);

	LPHOSTENT hostEntry;

	//store information about the server
	hostEntry = gethostbyname("hibbert");

	if(!hostEntry)
	{
		sError("Failed gethostbyname()");
		//WSACleanup();
		return CS_ERROR;
	}

	//create the socket
	SOCKET theSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

	if(theSocket == SOCKET_ERROR)
	{
		sError("Failed socket()");
		return CS_ERROR;
	}

	//Fill in the sockaddr_in struct
	SOCKADDR_IN serverInfo;

	serverInfo.sin_family = PF_INET;
	serverInfo.sin_addr = *((LPIN_ADDR)*hostEntry->h_addr_list);

	serverInfo.sin_port = htons(8888);

	rVal=connect(theSocket,(LPSOCKADDR)&serverInfo, sizeof(serverInfo));
	if(rVal==SOCKET_ERROR)
	{
		sError("Failed connect()");
		return CS_ERROR;
	}

	char *buf = "simpleservermessage\n";

	rVal = send(theSocket, buf, strlen(buf), 0);

	if(rVal == SOCKET_ERROR)
	{
		sError("Failed send()");
		return CS_ERROR;
	}


	closesocket(theSocket);
	cout << "closing client"<< endl;
	WSACleanup();
	
	return CS_OK;
}

void sError(char *str)
{
	MessageBox(NULL, str, "SOCKET ERROR", MB_OK);
	WSACleanup();
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Emiliano
Web Developer
United Kingdom United Kingdom
No Biography provided

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150901.1 | Last Updated 26 Apr 2003
Article Copyright 2003 by Emiliano
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid