Click here to Skip to main content
12,241,861 members (52,021 online)
Click here to Skip to main content

Stats

371.4K views
12.4K downloads
183 bookmarked
Posted

Server Client Sockets

, 25 Apr 2003
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
Web02 | 2.8.160426.1 | Last Updated 26 Apr 2003
Article Copyright 2003 by Emiliano
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid