Click here to Skip to main content
15,860,972 members
Articles / Desktop Programming / MFC
Article

Serializing classes across a network socket (TCP/IP)

Rate me:
Please Sign up or sign in to vote.
4.64/5 (11 votes)
7 Mar 2004Public Domain2 min read 97.9K   2.4K   37   15
This article gives example and code for sending a class across a network connection using TCP/IP and the CBlockingSocket class.

Introduction

This article shows you how to serialize a class or standard variable over a TCP/IP socket connection. It shows an example of how to setup the TCP/IP connection, setup other needed classes, and send/receive data over the socket.

I pulled from the MFC class CSocketFile. As you may know, CSocketFile lets you send and receive data to/from a network connection using a CArchive. The drawback is that the implementation of CSocket that is used has 16 bit code in it - not good for any decent application.

So I basically re-wrote them using CBlockingSocket (instead of CSocket) which uses 32 bit code and is better optimized. This allows you to attach a CArchive to an open CSocketFile and then serialize data to and from it (thus sending an receiving the data across the network).

Details

Here are the basic steps:

  1. Create and connect a CBlockingSocket object to the computer you want to send/receive data with
  2. Create a CBlockingSocketFile and attach it to the CBlockingSocket object you created in step 1 above.
  3. Create a CArchive object and attach it to the CBlockingSocketFile object you created in step 2 above.
    NOTE: You must create 1 CArchive for sending and 1 for receiving.
  4. Send your data or classes using the CArchive object created in step 3. You can send any serializable class or raw variables.
    VERY IMPORTANT NOTE: make sure you flush the CArchive object after you’re done sending data. This ensures all data is written across the network and tells the socket at the other end to go ahead and receive it.
  5. Close out the CArchive objects and the CBlockingSocket object. NOTE: Don’t close the CBlockingSocketFile object or it will assert.

Example code

// Step 1: Create CBlockingSocket and connect
CSockAddr sockAddr("127.0.0.1", SERVER_PORT);
CBlockingSocket socket; socket.Create();
socket.Connect(LPSOCKADDR(sockAddr));
 
// Step 2: Create socket file and attach
CBlockingSocketFile sockFile(&socket);

// Step 3: Create CArchive and attach
CArchive arSend(&sockFile, CArchive::store ); // use store to send data
CArchive arRecv(&sockFile, CArchive::load); // use load to receive data

// Step 4: Send the data using the archive
unsigned int uiCommand = 9;
CString strText("Some text to send");
arSend << uiCommand;
arSend.Flush();
strText.Serialize(arSend);
arSend.Flush();
 
// Step 4 (optional): Receive response
strText.Serialize(arRecv);
 
// (optional) Display received text
MessageBox(LPCTSTR(strText), "Response from socket", MB_OK);
 
// Step 5: Close up connection
arSend.Close(); 
arRecv.Close();
socket.Close();

Conclusion

That’s basically it. Of course, I’m making one assumption that there’s a listening socket on the other end ready to send/receive the data. For convenience I’ve added an appendix below with the code to setup a listening (server) socket and receive the data then send an acknowledgment.

In the future I may derive from CArchive and add functionality to make this whole process even easier, but for now I think this is pretty straight forward. Enjoy and happy coding!

Appendix A – Setup a listening (server) socket

// TCP/IP variables
CBlockingSocket listenSocket;
CSockAddr saServer;
CBlockingSocket clientSocket; // socket that is connected 
    // to the client for communication.
CSockAddr clientSA; // client socket address class
UINT uiCommand; // command received from TCP
CString strText; // for receiving / sending over socket connection

// TCP/IP - Initialize the listening socket
try{
    // socket initialization
    CSockAddr saServer(INADDR_ANY, SERVER_PORT);
    listenSocket.Create();
    listenSocket.Bind(saServer);
    listenSocket.Listen();
}catch(CBlockingSocketException *e) {
    listenSocket.Cleanup(); // cleanup socket (this won't throw an exception)
    return;
}
    
// Accept will block until an incoming client connection is 
// received. You can put this in a loop or 
// spawn child threads to handle multiple client request
if(!listenSocket.Accept(clientSocket, clientSA)){
// Accept failed, log the failure
    DEBUG_LOG2("CScheduler::run(): Accept failed with code: ", 
      WSAGetLastError());
}
        
// Receive the incoming data

// Create & attach a CBlockingSocketFile
CBlockingSocketFile sockFile(&clientSocket);

// Create/attach a CArchive for sending / receiving
CArchive arSend(&sockFile, CArchive::store);
CArchive arRecv(&sockFile, CArchive::load);

// Receive integer
arRecv >> uiCommand;

// Receive CString data
strText.Serialize(arRecv);

// Send acknowledgment
strText = "Integer and text received";
strText.Serialize(arSend);
arSend.Flush(); // very important to flush all sent data

// close connection
arSend.Close();
arRecv.Close();
// Close receiving client socket (don't close socket file 
// or else exception will be thrown)
clientSocket.Close();

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication


Written By
Software Developer (Senior)
United States United States
Became hooked on programming in the 3rd grade using basic. Programming in C/C++ since 1997.

This year I worked on a three person team to create a distributed computing system that predicts stock prices using an Artificial Neural Network. We used Encog as the ANN framework and Scoop as the distributed computing framework.

Prior to that, I created a proof of concept augmented reality game engine that runs on mobile platforms. The aim of that project was to create a MMO augmented reality system that would allow users to create their own game scenarios and virtual worlds in an augmented reality space. The project was coded using Objective-C, OpenGL, REST web-services and MySQL.

Fluent in the following languages and frameworks:
PHP
Python
HTML and CSS
Javascript
JQuery
MySQL
C / C++
Objective-C
FANN (ANN Framework)
Encog (ANN Framework)
Scoop (Distributed Computing Framework as a Python module)
iOS Framework
Cake PHP
Django

Comments and Discussions

 
GeneralIP 6 Version Pin
Kozlov_Sergey23-Mar-11 3:05
Kozlov_Sergey23-Mar-11 3:05 
QuestionCan this be used to send from c++ to .Net app Pin
mezik16-Dec-10 2:29
mezik16-Dec-10 2:29 
QuestionServer efficiency question Pin
cternoey1-Jun-07 23:00
cternoey1-Jun-07 23:00 
Generalstructure sending Pin
mahesh kumar s20-Nov-06 2:45
mahesh kumar s20-Nov-06 2:45 
GeneralRe: structure sending Pin
Gunni5-Dec-06 1:12
Gunni5-Dec-06 1:12 
I'm pretty new at this but it seems to me that sending pointers would be completely useless since even though you could send them the memory adresses they reference would contain other data and the pointer would therefore be useless.

So I think the simple answer is: No you cant send pointers over TCP Smile | :)
GeneralPointers across tcp/ip Pin
mahesh kumar s16-Nov-06 21:01
mahesh kumar s16-Nov-06 21:01 
QuestionUsing CBlockingSocket as replacement for CSocket Pin
Leonhardt Wille12-Feb-06 11:17
Leonhardt Wille12-Feb-06 11:17 
AnswerRe: Using CBlockingSocket as replacement for CSocket Pin
Leonhardt Wille4-Apr-06 2:07
Leonhardt Wille4-Apr-06 2:07 
GeneralException cleanup Pin
tom_or6-Sep-04 1:19
tom_or6-Sep-04 1:19 
Generalerror C2039: 'Serialize' : is not a member of 'CString' Pin
phamchicong23-May-04 18:22
phamchicong23-May-04 18:22 
GeneralRe: error C2039: 'Serialize' : is not a member of 'CString' Pin
Mikey_E25-May-04 7:10
professionalMikey_E25-May-04 7:10 
GeneralRe: error C2039: 'Serialize' : is not a member of 'CString' Pin
RancidCrabtree7-Sep-05 11:01
RancidCrabtree7-Sep-05 11:01 
GeneralRe: error C2039: 'Serialize' : is not a member of 'CString' Pin
Hwa Seon Shin (L544)4-Nov-05 5:23
Hwa Seon Shin (L544)4-Nov-05 5:23 
GeneralCSocket 16-Bit limitations Pin
Joe Calkins16-Mar-04 17:37
Joe Calkins16-Mar-04 17:37 
GeneralRe: CSocket 16-Bit limitations Pin
Mikey_E17-Mar-04 5:30
professionalMikey_E17-Mar-04 5:30 

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.