Chapter 1

gazecummingΔίκτυα και Επικοινωνίες

26 Οκτ 2013 (πριν από 3 χρόνια και 11 μήνες)

106 εμφανίσεις

Lab.09


Data transmission using WinSock


1.

Experiment purpose

(1)

Understand TCP/IP

(2)

Understand the concept and the role of WinSock and practice the method approaching
WinSock using MFC

(3)

Embody chatting program between computers using CasyncSocket


2.

Theory

(1)

What is
TCP/IP?

TCP and IP were developed by a Department of Defense (DOD) research project to connect a
number different networks designed by different vendors into a network of networks (the
"Internet"). It was initially successful because it delivered a few bas
ic services that everyone
needs (file transfer, electronic mail, remote logon) across a very large number of client and
server systems. Several computers in a small department can use TCP/IP (along with other
protocols) on a single LAN. The IP component pr
ovides routing from the department to the
enterprise network, then to regional networks, and finally to the global Internet. On the
battlefield a communications network will sustain damage, so the DOD designed TCP/IP to be
robust and automatically recover
from any node or phone line failure. This design allows the
construction of very large networks with less central management. However, because of the
automatic recovery, network problems can go undiagnosed and uncorrected for long periods of
time.

As with

all other communications protocol, TCP/IP is composed of layers:



IP
-

is responsible for moving packet of data from node to node. IP forwards each packet based
on a four
-
byte destination address (the IP number). The Internet authorities assign ranges of
numbers to different organizations. The organizations assign groups of their numbers to
departments. IP operates on gateway machines that move data from department to organization
to region and then around the world.



TCP
-

is responsible for verifying the

correct delivery of data from client to server. Data can be
lost in the intermediate network. TCP adds support to detect errors or lost data and to trigger
retransmission until the data is correctly and completely received.



Sockets
-

is a name given to t
he package of subroutines that provide access to TCP/IP on most
systems.


(2)

The concept and role of WinSock

In the
process

of
development of internet from ARPANET, DARPA (
Defense Advanced
Research Projects Agency)

was expecting to use the protocol supportin
g internet in UNIX OS
which many computers was using that time. They supported to make a layer of socket in
BSD
(Berkeley

Software Distribution) Unix. Ever since that time, TCP/IP is used in most of the
work
-
station. WinSock is a something modified from UN
IX OS to Windows OS.
Speaking in
easy
English
, WinSock can be thought to be a collection of
API (
Application Programming
Interface
), which is used in making TCP/IP applications in Windows,

and a standard documents
which is arranged and standardized and ope
ned to the public. The initial intension of the
development of WinSock was to suggest and support a consistent
network
-
programming

model
to various OS made by Microsoft. In other words, it was made to supply a method for making a
program consistently on TC
P/IP. Figure 1 shows the location of WinSock and relation to MFC
class library in TCP/IP. As you can see in Figure 1, WinSock performs the role of passing data
between application layer and TCP layer.


TCP/IP Structure












Application

layer




















Transport layer











Internet layer




















Physical layer

< The location of WinSock and relation to MFC class library in TCP/IP >

(3)

The structure of WinSock

WinSock support point
-
t
o
-
point communication with other
computers.
Because it is based on
TCP/IP, the user should know the IP address and port number required for communication with
the companion. The usual flow of WinSock using TCP/IP is like figure 2. At first, the server
crea
te socket and keep

listen


state and wait for the request from clients. When a client wants
to connect to the server, he also creates a socket and tries to connect. When the connection is
MFC
Soc
ket Class

Window Socket API

TCP layer

IP layer

Hardware Interface (Ethernet,etc)

TCP/IP application

successful, server accepts the request and creates a new socket and

connects it to the requested
connection. The
socket, which

was in

listen


state, is still in the same state and responds other
requests. You should pay attention to the fact that in a server, there

s a socket for listen and
another socket which is used i
n real communication. A server and a client
are

classified only by
functional meaning, and anyone of two similar computers can be a server. In other words, the
computer, which performs main part,

is server.

SERVER

CLIENT
























<

WinSock
flow using TCP >





socket()


c r e a t e s o c k e t


b
in
d()

give a name to socket

listen()

wait for the request

from
clients

W
aiting


accept(
)

when a request comes, create a new socket


and connects it to the client. The original

socket waits for a new connection
.

send()/receive()

data transmission

closesocket()

conne
ction

terminates


socket()

create socket

connect()

try to connect

send()/receive()

data transmission


closesocket()

connection

terminates

(4)

Classes supporting WinSock in MFC

MFC (Microsoft Foundation Class)

are classes that
Microsoft

made for the convenience of
users. WinSock is embodied by two types, and is supported to b
e easy for users. The two types
are CAsyncSocket and CSocket. In this experiment, we will use CAsyncSocket class. Next
functions are member functions of CAsyncSocket class and virtual functions which
can

be
overridden
.

Create() :
create sockets.

GetSockOp
t()/SetSockOpt() :
acquire or set various features of socket

Accept() : accept a request


Connect() :
try to connect


Close() :
close socket


Receive() :
accept data


Send() : transmit

data


OnAccept() :
This function is called when a request is
accepted.


OnReceive() :
This function is called when data come.


OnSend() :
This function is called when it is ready to send data.

OnClose() :
This function is called when the connected socket of companion is closed.


Usually to use these classes, w
e should inherit the original one and embody again the
required functions in each case. We perform these tasks in Main Lab.


(5)

Making a new class and overriding member function

The tasks each users want to use are very different each other. So in MFC, users

can derive and
utilize the class proper for his tasks based on CAsyncSocket class. In this section, we will
explain the method to make a new class in Visual C++ 6.0
environment

and to override the old
class member function in new class.

a.

method to make a
new class


.
Load
ClassWizard
.
(View
-
>ClassWizard or ctrl
-
w) ClassWizard

is an
instrument to help the tasks as creating class, member functions, member variables,
message map without direct typing.



.
Click the button,

Add Class
…’

and select

new
…’
.


.

Type the name you want and select CAsyncSocket class as base class. Now you
created a new class derived from CAsyncSocket. Click the

class tab


in left side of
Workspace and you can confirm that the class you made is registered.

b.

Overriding

Select the cla
ss you created in Class
Wizard
. You can see many items
in Message
window, and select one message and click ‘
Add
Function’.
Now you can override the
member function. For example, if you want to override OnReceive(), select the
OnReceive among messages and c
lick

Add Function

.

3.

Pre_Lab

(1)

Investigate about the role of WinSock

(2)

Investigate the concept of inheritance in C++ and
virtual

function.

(3)

Investigate the difference of TCP protocol and UDP protocol.

(4)

Explain precisely about OnAccept , OnClose, OnConnect, OnRe
ceive, OnSend which are
functions called in CAsyncSocket
class

by various events.

(5)

Investigate the prototype of
Create(), Listen(), Connect(), Accept(), Send(), Receive()

and
their meaning.

4.

Main_Lab

-

In this tutorial, the author
referred


Visual C++ 6, p
erfect guide


by Yong
-
Sung Kim for the
concrete process to embody the program. I suppose that you are a
beginner

of Visual C++, so
I

ll explain the initial step to begin a new project. But about the overall process, this material
provide only summary to co
nstitute the program, so it is strongly recommended that you should
refer the book of Yong
-
Sung Kim or other Visual C++ guide book to compete the
program.



(1)

Example of program and User Interface


i.

First, you should embody the structure of the
program
. S
elect SDI in class wizard,
and select window socket.
















ii.

Select CEditView as a Base class.














iii.

Now you should make a partition window. Create a new class CWriteView and
its

base class is also CEditView.

















Now, you hav
e a partition window like this figure.


From now on, we will add communication ability to this basic program.


(2)

Creation of socket classes in common use :

You should embody three
classes
. They are CserverSocket class, CDataSocket class,
CData
class. CServerSocket functions as an socket in a server class that accepts the request from a
client and connects the client and a data socket in the server. , CdataSocket is also a class
which inherits from Csocket class, and it performs the roll to

give and receive real data.
CData class includes data format which is necessary for each side during communication.

i.

Creation of CServerSocket class :

To make a
class, which can be,

used in common case, it is recommended to make a
program where a
task
-
rec
eiving

request is performedWhen a request comes to the
server, OnAccept function is called, and UM_Accept message is sent to main window
of program. You should make Init function to initialize the server socket.


class CServerSocket : public CSocket

{

//
Attributes

public:


//


// Overrides

public:


void Init(CWnd *pWnd, int nPortNum);


CWnd *m_pWnd;


// ClassWizard generated virtual function overrides


//{{AFX_VIRTUAL(CServerSocket)


public:


virtual void OnAccept(int nErrorCode);


//}}AFX_VIRTUAL



// Ge
nerated message map functions


//{{AFX_MSG(CServerSocket)



// NOTE
-

the ClassWizard will add and remove member functions here.


//}}AFX_MSG


// Implementation

protected:

};


In Init function, Create function is called to initialize the socket, and Listen

function
is called to start the connect request sensing.


void CServerSocket::Init(CWnd *pWnd, int nPortNum)

{


m_pWnd = pWnd;



Create(nPortNum);


Listen();

}


void CServerSocket::OnAccept(int nErrorCode)

{


m_pWnd
-
>SendMessage(UM_ACCEPT);




CSocket::O
nAccept(nErrorCode);

}


ii.

Creation of data socket CDataSocket class.

To make a class
which

is able to be used in common case, it is recommended to make
a program where OnReceive function doesn

t receive the data for itself and instead of it,
the function sen
d UM_DATARECEIVE message to main window and make the main
window could receive the data.

class CDataSocket : public CSocket

{

// Attributes

public:


CWnd


*m_pWnd;


CSocketFile *m_pFile;


CArchive

*m_pArchiveIn;


CArchive

*m_pArchiveOut;

// Operations

pub
lic:


CDataSocket();


virtual ~CDataSocket();


// Overrides

public:



void operator << (CData &data);


void operator >> (CData &data);


void Flush();


void Send(CData *pData);


void Receive(CData *pData);


void Init(CWnd *pWnd);


// ClassWizard generated v
irtual function overrides


//{{AFX_VIRTUAL(CDataSocket)


public:


virtual void OnReceive(int nErrorCode);


virtual void OnClose(int nErrorCode);


//}}AFX_VIRTUAL



// Generated message map functions


//{{AFX_MSG(CDataSocket)



// NOTE
-

the ClassWizard wil
l add and remove member functions here.


//}}AFX_MSG


// Implementation

protected:

};


And you should also embody a few functions, Init(CWnd * pWnd), Receive(CData *
pData), Send(CData * pData), OnReceive(int nErrorCode), OnClose(int nErrorCode)
etc. For m
ore detail, it

s recommended to refer Visual C++ guide book.

iii.

The data to be sent is prototyped in CData class .

class CData : public CObject

{

// Attributes

public:

//


public:


virtual void Serialize(CArchive &ar);


CString m_strData;

//


};

Serialize f
unction should be over
-
rided like this.

void CData::Serialize(CArchive &ar)

{


if(ar.IsStoring())


{



ar << m_strData;


}


else


{



ar >> m_strData;


}

}

iv.

Add the three classes in Component Gallery. When you should add the classes to
your chatting program

project.











First, you should add the socket class to your project. We will define the socket class as a
member variable of main frame. We will make a program which can perform as both client
and server.

class CMainFrame : public CFrameWnd

{

pro
tected:

//


public:


CSplitterWnd m_wndSplitter;


CServerSocket m_ServerSocket;


CDataSocket m_DataSocket;

// Operations

public:

//


};



(3)

Now you
shoul
d make the program be able to perform both as a server and as a client. It

s
very

difficult task, so it

s strongly recommended to refer other guide book for detail. In this
material, only a summary to constitute the program is provided. First you should initialize
the server socket and handle the ability to accept the request when a request comes. To
constit
ute this function, you need to handle with the UM_ACCEPT message. You should
also embody the ability as a client. You should prepare menu button to connect to server
and make a dialog box to input IP address and your name and port number. Your
program sh
ould be able to request connection to server and be able to give and take data
with the server. I
t’
s recommended to use commend message handler function of
OnConnect(). You also should set up the type of data to give and take. We made CData
class before, s
o set up the data as a member variable of CData. In this program we will use
only
sentences
, so it

s recommended to set up the data type as a CString. To send data,
modify the OnKeyDown(

). When a new data is received, OnReceive function in
CDataSocket is
called, and UM_DATARECEIVE message is sent to main frame. So you
should modify CMainFrame::OnReceive(

). Please refer other guide book for detail.




5.

Conclusion

We have made chatting program using WinSock. You might have checked that your computer can
com
municate with other computer. I guess, you might have had hard time to perform this experiment
if you are a beginner of Visual C++. But from now on, we will deal with transferring more various
types

of data. Good luck to you.