5,781,815 members and growing! (4,775 online)
Email Password   helpLost your password?
General Programming » Internet / Network » General     Intermediate License: The BSD License

Java Style Socket Programming in C++

By Vijay Mathew Pandyalakal

An article on socket programming in raw C++ on the Windows platform
VC6, C++, Windows, Java, MFC, Visual Studio, VS6, Dev

Posted: 11 Jul 2004
Updated: 15 Nov 2007
Views: 82,648
Bookmarked: 21 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
22 votes for this Article.
Popularity: 4.80 Rating: 3.57 out of 5
2 votes, 9.1%
1
3 votes, 13.6%
2
1 vote, 4.5%
3
3 votes, 13.6%
4
13 votes, 59.1%
5

Introduction

This article provides a C++ wrapper to the WINSOCK functions. The code consists of four classes; they are: CServerSocket, CSocket, CSocketAddress and CSocketException. These classes try to imitate Java socket classes whenever possible. They are designed to provide a very simple interface to sockets and I am sure you will find them useful in some way.

Using the Code

The first step in using the socket classes is to initialize the Windows socket library. This can by done by calling the CWinSock class's Initialize() static function. After using the socket classes, the library must be unloaded by calling the CWinSock class's Finalize() static function.

CWinSock::Initialize();

// socket calls


CWinSock::Finalize();

To create a server, declare an object CServerSocket and call its Accept() function. There are three constructors to CServerSocket. The default constructor that takes no argument and initializes the server to listen on port 80. A server also has a queue size, i.e. the number of connections that will wait in an internal queue for processing. This defaults to 10. Another constructor takes the port number as an argument. There is yet another constructor that receives the port number and queue size as arguments.

The Accept() function returns a pointer to CSocket. The application can use this pointer to communicate with the client. Use the Read() and Send() functions for this. Read() takes two arguments: a pointer to a character buffer and an integer that specifies the number of bytes to read. It is the caller's duty to initialize this buffer. Send() takes a pointer to a character buffer as its argument. This is the data to write to the network. After all reading and writing is over, it is the caller's duty to delete the CSocket object. The following snippet illustrates a simple server that accepts a single connection.

// headers required by socket classes in sock.h

#include < string>

#include < vector>

using namespace std;
#include < windows.h>


#include "sock.h"

using namespace openutils;

int main() 
{
  CServerSocket server(100); // server listening on port 100

  CSocket* client = server.Accept(); // accepting a client

  char *buffer = new char[100];
  client->Read(buffer,99); 
  // reads some data from client

  // client-> sends it back to the client

  delete client; // deletes the client socketr

  delete[] buffer;
  server.Close(); // closes the server

} 

In a real-world project, Accept() should be put in a separate thread and each new client socket should be handled by a new thread. For more details on creating threads in C++, see my article Synchronized multi-threading in C++ (No MFC!) on CodeProject.com. To create a client socket, call the Connect() function of the CSocket class. Here is a short example:

CSocket client;
client.Connect("http://www.yahoo.com",80);
client.Send("GET / HTTP 1.1 \r\n");
client.Read(buffer,(BUFF_SZ-1));
printf("\n%s",buffer);
client.Close();

Of course, the above code does not send a valid HTTP request, but it demonstrates how a CSocket object can be used to connect to a running server and communicate with it. There is also a utility class called CSocketAddress. The CSocket class has an embedded object of CSocketAddress. You can get a pointer to this object by calling the GetAddress() function of CSocket. Using this pointer, you can retrieve useful information about the server that the CSocket is connected to, like its DSN, aliases (if any), IP address, etc. Also keep in mind that all socket code should be enclosed in a try-catch block that handles CSocketExceptions:

try 
{
    // socket calls

}
catch(CSocketException ex) 
{
    printf("\nError: %d,%s",ex.GetCode(),ex.GetMessage());
}

History

  • Created: July 08, 2004
  • Updated: November 15, 2007

License

This article, along with any associated source code and files, is licensed under The BSD License

About the Author

Vijay Mathew Pandyalakal



Occupation: Software Developer
Location: India India

Other popular Internet / Network articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 46 (Total in Forum: 46) (Refresh)FirstPrevNext
GeneralTypo in code for server app - wrong portmemberHarry1766:08 29 Jul '08  
GeneralProblem with example server applicationmemberMårten Palm2:04 18 Jul '08  
GeneralRe: Problem with example server applicationmemberVijay Mathew Pandyalakal21:16 18 Jul '08  
GeneralRe: Problem with example server applicationmemberMårten Palm1:30 20 Aug '08  
Questionsocketmemberthuyantt118:10 15 Nov '07  
GeneralBug......memberdubbele onzin5:01 14 Nov '07  
GeneralRe: Bug......memberVijay Mathew Pandyalakal18:16 14 Nov '07  
QuestionHow to join client and server in one program?membermaglev_tgv19:02 12 Nov '07  
AnswerRe: How to join client and server in one program?memberVijay Mathew Pandyalakal18:37 13 Nov '07  
GeneralSend Unsigned charmemberwira1guys19:36 25 Sep '07  
GeneralRe: Send Unsigned charmemberVijay Mathew Pandyalakal19:06 26 Sep '07  
GeneralLicense and Usage of the CodememberJay Kint20:20 13 Jun '06  
GeneralRe: License and Usage of the CodememberVijay Mathew Pandyalakal22:27 13 Jun '06  
GeneralCan't build the codememberJim Archer14:42 30 Apr '06  
GeneralRe: Can't build the codememberVijay Mathew Pandyalakal17:41 1 May '06  
GeneralRe: Can't build the codememberJim Archer11:15 2 May '06  
GeneralRe: Can't build the codememberJim Archer16:46 7 May '06  
GeneralRe: Can't build the codememberVijay Mathew Pandyalakal17:56 7 May '06  
QuestionMultithreaded Server with Thread classmemberamdopteron10:28 2 Nov '05  
AnswerRe: Multithreaded Server with Thread classmemberVijay Mathew Pandyalakal3:25 3 Nov '05  
AnswerRe: Multithreaded Server with Thread classmemberamdopteron8:01 4 Nov '05  
GeneralI need help using socketmemberemsdell21:10 4 Jul '05  
GeneralRe: I need help using socketmemberVijay Mathew Pandyalakal19:22 5 Jul '05  
Generalhow do you traverse proxy's with this code?sussanonymous0:57 1 Jul '05  
GeneralRe: how do you traverse proxy's with this code?memberMars1053:03 15 Nov '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 15 Nov 2007
Editor: Genevieve Sovereign
Copyright 2004 by Vijay Mathew Pandyalakal
Everything else Copyright © CodeProject, 1999-2009
Java | Advertise on the Code Project