Click here to Skip to main content
11,437,265 members (64,290 online)
Click here to Skip to main content

Java Style Socket Programming in C++

, 15 Nov 2007 BSD
Rate this:
Please Sign up or sign in to vote.
An article on socket programming in raw C++ on the Windows platform

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

Share

About the Author

No Biography provided

Comments and Discussions

 
GeneralTypo in code for server app - wrong port Pin
Harry17629-Jul-08 6:08
memberHarry17629-Jul-08 6:08 
GeneralProblem with example server application Pin
Mårten Palm18-Jul-08 2:04
memberMårten Palm18-Jul-08 2:04 
GeneralRe: Problem with example server application Pin
Vijay Mathew Pandyalakal18-Jul-08 21:16
memberVijay Mathew Pandyalakal18-Jul-08 21:16 
GeneralRe: Problem with example server application Pin
Mårten Palm20-Aug-08 1:30
memberMårten Palm20-Aug-08 1:30 
Questionsocket Pin
thuyantt115-Nov-07 18:10
memberthuyantt115-Nov-07 18:10 
GeneralBug...... Pin
dubbele onzin14-Nov-07 5:01
memberdubbele onzin14-Nov-07 5:01 
GeneralRe: Bug...... Pin
Vijay Mathew Pandyalakal14-Nov-07 18:16
memberVijay Mathew Pandyalakal14-Nov-07 18:16 
QuestionHow to join client and server in one program? Pin
maglev_tgv12-Nov-07 19:02
membermaglev_tgv12-Nov-07 19:02 
AnswerRe: How to join client and server in one program? Pin
Vijay Mathew Pandyalakal13-Nov-07 18:37
memberVijay Mathew Pandyalakal13-Nov-07 18:37 
GeneralSend Unsigned char Pin
wira1guys25-Sep-07 19:36
memberwira1guys25-Sep-07 19:36 
GeneralRe: Send Unsigned char Pin
Vijay Mathew Pandyalakal26-Sep-07 19:06
memberVijay Mathew Pandyalakal26-Sep-07 19:06 
GeneralLicense and Usage of the Code Pin
Jay Kint13-Jun-06 20:20
memberJay Kint13-Jun-06 20:20 
GeneralRe: License and Usage of the Code Pin
Vijay Mathew Pandyalakal13-Jun-06 22:27
memberVijay Mathew Pandyalakal13-Jun-06 22:27 
GeneralCan't build the code Pin
Jim Archer30-Apr-06 14:42
memberJim Archer30-Apr-06 14:42 
GeneralRe: Can't build the code Pin
Vijay Mathew Pandyalakal1-May-06 17:41
memberVijay Mathew Pandyalakal1-May-06 17:41 
GeneralRe: Can't build the code Pin
Jim Archer2-May-06 11:15
memberJim Archer2-May-06 11:15 
GeneralRe: Can't build the code Pin
Jim Archer7-May-06 16:46
memberJim Archer7-May-06 16:46 
GeneralRe: Can't build the code Pin
Vijay Mathew Pandyalakal7-May-06 17:56
memberVijay Mathew Pandyalakal7-May-06 17:56 
QuestionMultithreaded Server with Thread class Pin
amdopteron2-Nov-05 10:28
memberamdopteron2-Nov-05 10:28 
AnswerRe: Multithreaded Server with Thread class Pin
Vijay Mathew Pandyalakal3-Nov-05 3:25
memberVijay Mathew Pandyalakal3-Nov-05 3:25 
AnswerRe: Multithreaded Server with Thread class Pin
amdopteron4-Nov-05 8:01
memberamdopteron4-Nov-05 8:01 
GeneralI need help using socket Pin
emsdell4-Jul-05 21:10
memberemsdell4-Jul-05 21:10 
GeneralRe: I need help using socket Pin
Vijay Mathew Pandyalakal5-Jul-05 19:22
memberVijay Mathew Pandyalakal5-Jul-05 19:22 
Questionhow do you traverse proxy's with this code? Pin
anonymous1-Jul-05 0:57
sussanonymous1-Jul-05 0:57 
AnswerRe: how do you traverse proxy's with this code? Pin
Mars10515-Nov-05 3:03
memberMars10515-Nov-05 3:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150428.2 | Last Updated 15 Nov 2007
Article Copyright 2004 by AnOldGreenHorn
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid