Click here to Skip to main content
15,892,059 members
Articles / Desktop Programming / MFC
Article

Java Style Socket Programming in C++

Rate me:
Please Sign up or sign in to vote.
4.26/5 (25 votes)
15 Nov 2007BSD2 min read 174.9K   3.5K   33   46
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.

C++
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.

C++
// 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:

C++
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:

C++
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


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralTypo in code for server app - wrong port Pin
Harry17629-Jul-08 5:08
Harry17629-Jul-08 5:08 
GeneralProblem with example server application Pin
Mårten Palm18-Jul-08 1:04
Mårten Palm18-Jul-08 1:04 
GeneralRe: Problem with example server application Pin
AnOldGreenHorn18-Jul-08 20:16
AnOldGreenHorn18-Jul-08 20:16 
GeneralRe: Problem with example server application Pin
Mårten Palm20-Aug-08 0:30
Mårten Palm20-Aug-08 0:30 
Questionsocket Pin
thuyantt115-Nov-07 17:10
thuyantt115-Nov-07 17:10 
GeneralBug...... Pin
dubbele onzin14-Nov-07 4:01
dubbele onzin14-Nov-07 4:01 
GeneralRe: Bug...... Pin
AnOldGreenHorn14-Nov-07 17:16
AnOldGreenHorn14-Nov-07 17:16 
QuestionHow to join client and server in one program? Pin
maglev_tgv12-Nov-07 18:02
maglev_tgv12-Nov-07 18:02 
AnswerRe: How to join client and server in one program? Pin
AnOldGreenHorn13-Nov-07 17:37
AnOldGreenHorn13-Nov-07 17:37 
GeneralSend Unsigned char Pin
wira1guys25-Sep-07 18:36
wira1guys25-Sep-07 18:36 
GeneralRe: Send Unsigned char Pin
AnOldGreenHorn26-Sep-07 18:06
AnOldGreenHorn26-Sep-07 18:06 
GeneralLicense and Usage of the Code Pin
Jay Kint13-Jun-06 19:20
Jay Kint13-Jun-06 19:20 
GeneralRe: License and Usage of the Code Pin
AnOldGreenHorn13-Jun-06 21:27
AnOldGreenHorn13-Jun-06 21:27 
GeneralCan't build the code Pin
Jim Archer30-Apr-06 13:42
Jim Archer30-Apr-06 13:42 
GeneralRe: Can't build the code Pin
AnOldGreenHorn1-May-06 16:41
AnOldGreenHorn1-May-06 16:41 
GeneralRe: Can't build the code Pin
Jim Archer2-May-06 10:15
Jim Archer2-May-06 10:15 
GeneralRe: Can't build the code Pin
Jim Archer7-May-06 15:46
Jim Archer7-May-06 15:46 
GeneralRe: Can't build the code Pin
AnOldGreenHorn7-May-06 16:56
AnOldGreenHorn7-May-06 16:56 
QuestionMultithreaded Server with Thread class Pin
amdopteron2-Nov-05 9:28
amdopteron2-Nov-05 9:28 
AnswerRe: Multithreaded Server with Thread class Pin
AnOldGreenHorn3-Nov-05 2:25
AnOldGreenHorn3-Nov-05 2:25 
AnswerRe: Multithreaded Server with Thread class Pin
amdopteron4-Nov-05 7:01
amdopteron4-Nov-05 7:01 
GeneralI need help using socket Pin
Member 17070284-Jul-05 20:10
Member 17070284-Jul-05 20:10 
I need help please…

I need to develop a sample a client server program doing summation and need to to satisfy the following requirement.

Server (summation-server.c)
1.Computes the sum of numbers inputted by the user through the client program (these numbers may either be integers or floating-point numbers);
2.During invocation from the command line, requires a port number where it will be listening for connection requests, and messages from the client;
3.Continuously runs in the background, listening for inputs from the client program until terminated by pressing Ctrl-C;
4.Understands the following messages received from the client:
o inputs <n> ..........where N is the number of numbers to do a
summation on.
o num <n>.................where n is one of the N numbers to sum
o sum .........................the sum of the N numbers
5.Does nothing if it does not understand the message;
6.Does input validation to reject invalid inputs;
7.Resets the environment variables after the sum was outputted on the screen.
8.State sensitive, meaning it cannot backtrack to any previous process. Process 4 needs to be satisfied before the server’s state cycles back to process 1.

For the Client (summation-client.c)
1.Description: Used to provide inputs to the server program;
2.During invocation from the command line, requires the machine name where the server is running, and the port number where the server is listening;
3.Automatically connects to the summation-server;
4.Continuously runs in the background, providing a means by which the user can send inputs to the summation server until terminated by pressing Ctrl-C;
5·Provides a command line prompt where the user can send text messages to the server;
6.Messages entered at the command line gets sent to the summation-server upon pressing the Enter key;
7·The valid messages that may be sent to the summation-server are those mentioned above, namely: inputs, num, and sum.
8·Does not do data entry validation; Meaning, the user is free to send any message to the summation-server.


This is the sample screen from what i understand based on the given requirements.

Sample server screens Sample client screens
prompt$ ./summation-server 31219 prompt$ ./summation-client latte 31219
Server is running... latte>_

prompt$ ./summation-client latte 31219
latte>inputs 2
latte>_
prompt$ ./summation-server 31219
Server is running...
Waiting for 2 numbers...
prompt$ ./summation-client latte 31219
latte>inputs 2
latte>num 100
latte>_
prompt$ ./summation-server 31219
Server is running...
Waiting for 2 numbers...
num1 is 100...

prompt$ ./summation-client latte 31219
latte>inputs 2
latte>num 100
latte>num 150
latte>_

prompt$ ./summation-server 31219
Server is running...
Waiting for 2 numbers...
num1 is 100...
num2 is 150.
prompt$ ./summation-client latte 31219
latte>inputs 2
latte>num 100
latte>num 150
latte>sum
latte>_
prompt$ ./summation-server 31219
Server is running...
Waiting for 2 numbers...
num1 is 100...
num2 is 150.
sum is 250.

Do you think it is correct with regards to my understanding how the program process?

But the requirements to solve this problem is use a C/C++ program. Please help with this…

Thanks in advance.


emmie
GeneralRe: I need help using socket Pin
AnOldGreenHorn5-Jul-05 18:22
AnOldGreenHorn5-Jul-05 18:22 
Questionhow do you traverse proxy's with this code? Pin
Anonymous30-Jun-05 23:57
Anonymous30-Jun-05 23:57 
AnswerRe: how do you traverse proxy's with this code? Pin
Alexandre Ravey15-Nov-05 2:03
Alexandre Ravey15-Nov-05 2:03 

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

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