a sync socket

5

Click here to load reader

Upload: nguyen-linh

Post on 21-May-2017

212 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: A Sync Socket

9,828,785 members (47,274 online) 276 Sign out

1 hushu

home quick answers discussions features community help Search for articles, questions, tip

Articles » General Programming » Internet / Network » General

Article

Browse Code

Stats

Revisions (8)

Alternatives

Comments &Discussions (2)

Add your ownalternative version

About Article

Goal: Describe howasynchronous or non-blocking TCP code works

Type Article

Licence CPOL

First Posted 27 Sep 2012

Views 8,556

Downloads 364

Bookmarked 14 times

VS2008 C++ Dev

Intermediate Win7

Top News

Hijacking airplanes with anAndroid phone

Get the Insider News free eachmorning.

Related Videos

Prev Next

Asynchronous TCP Part 2By bkelly13, 30 Mar 2013

Is your email address OK? You are signed up for our newsletters but your email address is eitherunconfirmed, or has not been reconfirmed in a long time. Please click here to have a confirmationemail sent so we can confirm your email address and start sending you newsletters again.

Alternatively, you can update your subscriptions.

Download MFC WINSOCK - 1.2 MB

PrerequisitesREAD PART 1. That is upper case and said with emphasis. This is rather long as it is so I must presume the readerhas read Part 1.

The reader is expected to know how to create an MFC project and the fundamentals of TCP/IP operations. (What isTCP/IP and its purpose, what are the client/server roles, IP address, ports, and the like.) The reader should be awell started Visual Studio beginner or maybe an intermediate VS user or better, confident with dialogs and theircontrols, but is expected to be a novice with asynchronous TCP/IP operation.

All Four ArticlesLate Addition: This is a short summary of all four articles and a link to each. I have completed four articles on asynchronous TCP/IP and Microsoft's class ASyncSocket. Part 1 describes thenecessary concepts. Part 2 describes a single project that incorporates a server and a client in a single project anda single dialog. The user can walk through a transaction one step at a time. In parts 3 and 4 the Server and Clientare separated into two projects residing in one solution. The Server and Client can run on separate computers.That project introduces the concept of multiple projects in a single solution. It introduces the concept of usingsource code from a separate directory. If you are not well versed in TCP/IP and with ASyncSocket, the first twoarticles are a must read. If you have not worked with multiple projects in one solution, or with Additional IncludeDirectories, Part 3 is must read. If that sentence looks weird, please read Part 3. Here is a link to each article. Asynchronous TCP Part 1 Asynchronous TCP Part 2 Asyncsocket Part 3: The Server Asyncsocket Part 4: The Client

IntroductionThis is the second of a two part how to article. Part 1 describes the concepts of how to use the Windows classCAsyncSocket to implement an asynchronous TCP/IP interface. It says away from the code as much as possible.That article is a must read before this article. It is found here.

This article presents the use of the class CAsyncSocket. The purpose of the application was to provide anapplication to hold and exercise class CAsyncSocket. In order to be able to see all the interactions in the dialog itwound up with over sixty controls, and could use more. Describing that many controls and the code to drive them istoo much for an article about CAsyncSocket. This article describes the three worker classes and omits the supportcode.

Three classes are required to initiate and carry on a TCP/IP conversation using Windows and CAsyncSocket. Inthis application they are C_Server, C_Client, and C_Server_Send_Time_Socket. Class C_Server contains anAccept() method, an CAsyncSocket::Accept() method, an OnAccept method, and anCAsyncSocket::OnAccept() method. To ensure the names were completely obvious, the methods in C_Serverthat might be confused with those of the base class are all prefixed with Class_. The same applies to the other twoclasses.

Having read Part 1, we jump right into class C_Server.

Class C_Server::Class_Initialize()There are three key methods in Class C_Server. Begin with the initialize method.

Collapse | Copy Code

bool C_Server::Class_Initialize(){ m_winsock_status = AfxSocketInit(); m_winsock_status == 0 ? m_method_status = false : m_method_status = true;

5.00 (1 vote)

articles

2013-4-24 Asynchronous TCP Part 2 - CodePr…

codeproject.com/…/Asynchronous-… 1/5

Page 2: A Sync Socket

French C# TutorialLesson 12 - Array part 3

French C# TutorialLesson 11 - Array part 2

Related ArticlesA Chat Application UsingAsynchronous TCP Sockets

Multi-threaded .NET TCPServer Examples

A Chat Application UsingAsynchronous UDP sockets

ZeroMQ via C#: Introduction

Remote Execution Using .NETRemoting

Absolute beginner'sintroduction to remoting

The Super Pool Framework

Asynchronous TCP Part 1

Asyncsocket Part 4: The Client

A simple IOCP Server/ClientClass

Developing a SOHO HTTP filterstep by step

A Complete TCP Server/ClientCommunication and RMIFramework in C# .NET -Implementation

Modbus TCP class

Communication options withWCF - Part 2

C# SocketAsyncEventArgsHigh Performance SocketCode

A TCP client that uses MSNprotocol

Programming Windows TCPSockets in C++ for theBeginner

Asyncsocket Part 3: The Server

Impersonation in anasynchronous threadedWebPart

TCP/IP Chat Application UsingC#

if( m_method_status ) { m_winsock_status = CAsyncSocket::Create( m_port_number, SOCK_STREAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, DEFAULT_IP_ADDRESS ); m_wsa_error = WSAGetLastError(); m_winsock_status == 0 ? m_method_status = false : m_method_status = true; } return m_method_status;}

There are only two worker lines in this method, the remainder is all support.

Collapse | Copy Code

m_winsock_status = AfxSocketInit();

m_winsock_status = CAsyncSocket::Create( m_port_number, SOCK_STREAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, DEFAULT_IP_ADDRESS );

The first tells Windows to perform a bunch of initialization for sockets operations. The seconds creates the socket.Almost all the work is done by the base class leaving only the high level calls to make.

Note the calls to WSAGetLastError() to check for problems. That must be done immediately after calls to the baseclass. If you are new to TCP/IP in windows, WSA error code merits some time with Google. In the followingdiscussion the support code will not be described.

Class C_Server::Class_Listen()After the socket operations are initialized, the next step is to tell Windows to begin listening for a client that willrequest a TCP/IP connection.

Collapse | Copy Code

m_winsock_status = Listen();

This is the only worker code in this method. After it returns, Windows has completed the TCP/IP initialization and isready for a client.

Here is where base class CAsyncSocket enables us to divert from simple blocking TCP/IP operations. Withsynchronous operations the call to Listen() would not return until Window has received a request from a client. Inasynchronous operations, Listen() returns with a status code allowing the application do other things whileWindows waits for a client connect.

Class C_Server::Class_Accept()This is the key method. Again, there are but two worker lines of code.

Collapse | Copy Code

mp_C_Server_Send_Time_Socket = new C_Server_Send_Time_Socket;

m_winsock_status = CAsyncSocket::Accept( *mp_C_Server_Send_Time_Socket );

First up is to create an instance of C_Server_Send_Time_Socket. This is the object that will carry on all theconversations with the client. It is customized for each particular application.

Very Important Paragraph

Next up, tell Windows that this is the object for communicating with the client. To do that we call the Accept() methodof the base class and pass in our new object as the only argument. The base class and Windows manage all thedetails. The responsibility to handle all communications with the client is hereby assigned to the new object. Thatsecond line of code is so simple, but so key to this process, you should pause and consider this a few momentsbefore continuing.

If your application expects a single client, this will work for you. However, and this is a big however, if you willaccept multiple client connection, the C_Server class will need to do something with the pointer to the new object itcreated and will need code to recycle and be prepared for the next connection. For simplicity, this application willhandle one client only.

That is it. Much more simple than I expected.

Class C_Server::Class_Close()The Close() operation is rather straight forward.

Class_C_Server::On*()In the CodeProject article referenced in Part 1 and in other places, I found this list of methods from the base classthat are to have over-ride methods. Here is their declaration from the dot H file.

Collapse | Copy Code

virtual void OnAccept( int nErrorCode );

2013-4-24 Asynchronous TCP Part 2 - CodePr…

codeproject.com/…/Asynchronous-… 2/5

Page 3: A Sync Socket

p ( ); virtual void OnClose( int nErrorCode ); virtual void OnConnect( int nErrorCode ); virtual void OnOutOfBandData( int nErrorCode ); virtual void OnReceive( int nErrorCode ); virtual void OnSend( int nErrorCode );

For this very simple demo application, the definitions are very simple. This one is typical.

Collapse | Copy Code

void C_Server::OnAccept(int nErrorCode){ m_server_on_accept_count ++; mp_main_dialog‐>Set_Server_On_Call_Counts( m_server_on_accept_count, m_server_on_close_count, m_server_on_connect_count, m_server_on_out_of_band_count, m_server_on_receive_count, m_server_on_send_count ); if(nErrorCode==0) { CAsyncSocket::OnAccept(nErrorCode); }}

All of the On*() methods in each class has a counter that increments on each entry, and a method call to the maindialog so it will immediately display the call count. All the classes have identical declarations and essentially identicaldefinitions.

The reader can begin with this demo application then add complexity and see when, or if, each of the methods iscalled.

C_Server_Send_Time_Socket::Class_Send()As noted this class is created by the C_Server::Class_Accept() method. Windows and the base class manageof all the details. After being handed to the base class as the argument, the object is ready to handle all thecommunications with the client.

Collapse | Copy Code

int C_Server_Send_Time_Socket::Class_Send( ){ int chars_sent = 0; int size = sizeof( m_current_time ); GetSystemTime( &m_current_time ); chars_sent = CAsyncSocket::Send( (const void *) &m_current_time, size, 0 ); return chars_sent;}

This method fetches the current system time, then tell the base class to send it. Sending the complete structure tothe client makes it simple.

Look through the remaining methods of this class and discover that all the remaining code is support for the demoapplication. None is needed for the core function to send data.

Again, in this simple application, that is all there is.

C_Client::Class_Initialize()The client initialization is rather simple.

Collapse | Copy Code

m_winsock_status = AfxSocketInit( NULL ); m_winsock_status = Create();

Again, there are just two worker lines of code.

C_Client::Class_Connect()Here is our one worker bee.

m_winsock_status = CAsyncSocket::Connect( m_ip_address, m_port_number );

When this method is initiated the base class goes to Windows and its APIs and sends out a search party to find theserver. This sets off several events. In C_Server the OnAccept() method is called. That tells the C_Server objectthat it now has a live client. The server responds across the network and C_Client gets a message that the serverhas been found. The MFC application detects this message and knows to call the client method OnConnect().When you run the application that counter will advance to 1 (one). You can write code in this method to respond tothe connect event.

All these interactions at the Windows level results in the client OnSend() being called. While the client methodOnConnect() means that we have connected, OnSend() means that we can now send to the server.

As noted earlier, this application is simple enough that, other than counting them, all the On*() method calls areignored. In this application the user and the keyboard close the loops. In a real application there will be code toclose the loops and make it all functional.

In standard code, this is a blocking call and the application waits until the server has been found. ClassCAsyncSocket allows the client application to attend to other matters while waiting for responses.

2013-4-24 Asynchronous TCP Part 2 - CodePr…

codeproject.com/…/Asynchronous-… 3/5

Page 4: A Sync Socket

Article Top

0 TweetRate this: Poor Excellent Vote

C_Client::Class_Receive()Again, this is almost too simple.

Collapse | Copy Code

int chars_received = 0;int size = sizeof( m_current_time );chars_received = CAsyncSocket::Receive( (void *) &m_current_time, size, 0 );

The client has an identical time structure to that of server and simply reads the data into that structure. The code todisplay the time is deliberately left out of this method for simplicity. Check out method SYSTEMTIMEC_Client::Class_Get_Time() and its caller to see how this is handled.

ConclusionWhen considering the lengths and the difficulty in getting this together for the first time, the actual operations arerather simple. (Recognizing that there is much to de before you have a working TCP/IP real world application.)

A quick review is in order.

1. Initialize C_Server.2. Initiate the server Listen mode, instructing Windows to listen for a client.3. Initialize C_Client.4. Initiate the connect method, instructing Windows to find and connect to the server.5. In the Server, Accept() the connection and create class C_Server_Send_Time_Socket to communicate

with the client.6. Use C_Server_Send_Time_Socket to send information to the client.7. In the Client, receive the information.

Observe that there are seven steps here, and there are seven buttons in the application. The matchup is one toone. I suggest you put a break point in each of the methods of each class then start with 1:Initialize and see whereyou get. (Return to Part 1 for a walkthrough.) Remove each breakpoint as you get to it, then step through the codeuntil you get back to the Windows MFC application code (the stuff you did not write). Then hit Continue in thedebugger, check the results, and go on to the next button. Go back to Part 1 for a better walk through of theseactivities.

To repeat an earlier comment, it works much better when you put the application dialog on one monitor while youstep through the debugger in Visual Studio on the other monitor.

LicenseThis article, along with any associated source code and files, is licensed under The Code Project Open License(CPOL)

About the Author

bkelly13

United States Member

My career began as a navigation electronics technician onsubmarines in the U.S. Navy. (After a short stint on thebattleship USS New Jersey, that was cool.) I worked the nextseveral years as a technician while earning a BSCS incomputer science. During my senior year I wrote code for partof a missile flight simulator. That was followed by too manyyears working with Fortran on the security system at CapeCanaveral Air Force Station. I worked a few years on CLCS(Checkout and Launch Control System for the space shuttle)until it was canceled by NASA, then became the lead antenna engineer for a portable range tracking system. Now Iwork on telemetry at an Air Force base.If you work with telemetry please check out this BB: www.bkelly.ws/irig_106 and the support pages atwww.bkelly.ws/irig. Thank you.

Comments and Discussions

2013-4-24 Asynchronous TCP Part 2 - CodePr…

codeproject.com/…/Asynchronous-… 4/5

Page 5: A Sync Socket

Permalink | Advertise | Privacy | Mobile Web02 | 2.6.130416.1 | Last Updated 29 Mar 2013

Article Copyright 2012 by bkelly13Everything else Copyright © CodeProject, 1999-2013

Terms of Use

Layout: f ixed | f luid

Add a Comment or Question Search this forum Go

Profile popups Spacing Relaxed Noise Medium Layout Normal Per page 25 Update

First Prev Next

Jochen Arndt 27 Sep '12 - 16:43

bkelly13 28 Sep '12 - 4:09

Last Visit: 30 Mar '13 - 1:12 Last Update: 24 Apr '13 - 21:27 Refresh 1

General News Suggestion Question Bug Answer Joke Rant Admin

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

Wrong Title

Re: Wrong Title

2013-4-24 Asynchronous TCP Part 2 - CodePr…

codeproject.com/…/Asynchronous-… 5/5