Socket programming in Windows

Source: Internet
Author: User
Socket
Programming in Windows

When you are familiar with network programming in the Unix
Environment, understanding Windows Network Programming is easy. This section
Describes the relationship between the windows network programming interface and
The UNIX network programming model, and how windows socket programming has
Formed the foundation of the. NET Framework network classes.

Windows Socket Functions

It makes sense that the windows network programming model is
Derived from the comparable UNIX model. extends features of the Windows Operating
Systems have their roots in Unix systems. Much of Windows Network Programming
Was modeled after the Unix Berkeley socket method. It was called, not
Surprisingly, Windows Sockets, or Winsock for short. The Winsock interface was
Designed to allow network programmers from the Unix environment to easily Port
Existing network programs, or to create new network programs in the windows
Environment without a large learning curve.

The Winsock apis were implemented as a set of header and Library
Files for developers and DLL files to be used by applications. There are two
Basic Winsock library versions: The 1.1 version was originally released
Windows 95 workstations and provided basic socket functionality. Later, version
2 was released as an add-on for Windows 95 machines. It added significantly more
Socket functions and protocols that cocould be deployed by network programmers.
The Time Windows 98 was released, the Winsock Library had matured to version
2.2, which is still a part of the current Windows operating system releases.

Note

The lone exception to this arrangement is the Windows CE
Platform. At this writing, Windows CE still only supports the Winsock 1.1
Libraries.

The core of the Winsock environment is, of course, the socket.
Just as in UNIX, all windows network programs create a socket to establish
Link with the underlying network interface on the Windows system. All of
Standard socket function callemployed in the Unix world were ported to
Windows system. However, there are a few differences between Unix sockets and
Winsock. The following sections describe these differences.

Wsastartup ()

To begin a Winsock program, you make a call to the wsastartup () function. This function informs the operating
System which Winsock version the program needs to use. The OS attempts to load
The appropriate Winsock library from which the socket functions will
Operate.

The format of the wsastartup () function
Is as follows:

int WSAStartup(WORD wVersion, LPWSDATA lpWSAData)

The first parameter defines the required version for the program.
If the program requests Version 2.2 of WinSock and only version 1.1 is
Available, The wsastartup () function will return
Error. However, if the application requests version 1.1 and Version 2.2 is
Loaded, the function will succeed.

When the function succeeds,LpwsadataParameter points to a structure that will
Contain information regarding the Winsock library after it's loaded, such as
Actual Winsock version used on the system. This information can be then be used
Determine the network capabilities of the system the program is running
On.

Wsacleanup ()

A Winsock program must release the Winsock library when it
Is finished. The wsacleanup () function is used at
End of each Winsock program to indicate that no other Winsock functions will be
Used, and the Winsock library can be released. The wsacleanup () function does not use any parameters, it just
Signals the end of the Winsock functions in the program. If any Winsock
Functions are used after the wsacleanup () function,
Error condition will be raised.

Winsock Functions

In between the wsastartup () and
Wsacleanup () functions, the Winsock program can behave
Just like the UNIX socket program, using socket (),
BIND (), connect (), listen (), and accept () CILS. In
Fact, the Winsock interface uses the same structures for addresses (sockaddr_in) and the same values to define protocol families
And types (such as the sock_stream protocol family)
UNIX does. The goal of this was to make porting UNIX network programs to
Windows environment as easy as possible.

In addition to the standard UNIX network functions, the Winsock
Version 2 interface provided des its own set of network functions, all preceded
WSA. These functions extend the functionality of the standard UNIX Network
Functions. For example, the wsarecv () function can be
Used in place of the standard UNIX Recv () function
Call. wsarecv () adds two additional parameters to
Original function call, allowing for the windows-specific functionality
Creating overlapped I/O and partial datatives. Figure 3.4 shows
How the Winsock WSA functions can be used to replace standard UNIX functions.

Winsock non-blocking Socket Functions

Another similarity to the UNIX network environment is that
Winsock supplies ways to prevent network I/O functions from blocking the program
Execution. Winsock supports the standard UNIX methods of setting a socket
Non-blocking mode using the ioctlsocket () function
(Similar to the Unix fcntl () function) and the select () function to multiplex multiple sockets.

The ioctlsocket () format is as follows:

ioctlsocket(SOCKET s, long cmd, u_long FAR* argp)

The socket to be modified isS,CMD
Parameter specifies the operation to make on the socket, andArgpParameter specifies the command
Parameter.

In addition to these standard socket functions, the Winsock
Interface offers additional methods of allowing non-blocking network I/O.

Wsaasyncselect ()

One of the features that differentiates windows from
Standard UNIX programs is the conceptEvents. Unlike
Common structured programs that have a set way of executing, Windows programs
Are usually Event Driven. methods are executed in the program in response
Events occurring while the program is running-buttons are clicked, menu items
Are selected, and so on. The standard technique of waiting around for data
Occur on network sockets does not fit well in the Windows event model.
Event-driven access to network sockets is the answer.

The wsaasyncselect () function expands on
The standard UNIX select () function by allowing windows
To do the work of querying the sockets. A wsaasyncselect () method is created that includes des the socket
To monitor, along with a Windows message value that will be passed to the window
When one of the socket events occurs (such as data being available to be read,
Or the socket being ready to accept written data). The format of the wsaasyncselect () function is as follows:

int WSAAsyncSelect(SOCKET s, HWND hWnd,
unsigned int wMsg, long lEvent)

The socket to monitor is defined bySParameter, and the parent window to receive the event
Message is definedHwnd.
Actual event to send is defined byWmsgParameter. The last parameter,Levent, Defines the events
Monitor for the socket. You can monitor more than one event for a socket
Specify a bitwise OR of the events shown in table 3.4.

Table 3.4: wsaasyncselect () event types

Event

Description

FD accept

A new connection is established with
Socket.

FD address list change

The local address list changed for the socket's Protocol
Family.

FD close

An existing connection has closed.

FD connect

The socket has completed a connection with a remote
Host.

FD group QoS

The socket group's quality of service value has
Changed.

FD OOB

The socket has stored ed out-of-band data.

FD QoS

The socket's quality of service value has
Changed.

FD read

The socket has data that is ready to be read.

FD routing interface change

The socket's routing interface has changed for a specific
Destination.

FD write

The socket is ready for writing
Data.

An example of the wsaasyncselect ()
Function wocould look like this:

WSAAsyncSelect(sock, hwnd, WM_SOCKET, FD_READ | FD_CLOSE);

In this example, if the socket has data available to be read,
Or if it detects that the remote host closed the connection, the wm_socket message wocould be sent toHwndWindow in the wparam of the window message. It wocould then be
Responsibility ofHwndWindow
To detect and handle the wm_socket message and perform
The appropriate functions depending on which event was triggered. This is almost
Always handled in a Windows procedure (windowproc)
Method for the window using case statements.

Wsaeventselect ()

Instead of handling socket communications using Windows
Messages, The wsaeventselect () usesEvent object handle. The event object handle is
Self-contained method defined in the program that is called when a unique event
Is triggered. This technique allows you to create separate windows methods
Handle the varous socket events.

For this technique to work, a unique event must first be defined
Using the wsacreateevent () function. After the event is
Created, it must be matched to a socket using the wsaeventselect () function:

WSASelect(SOCKET s, WSAEVENT hEvent, long lNetworkEvents)

As usual,SParameter defines the socket to monitor, andHeventDefines the created event
That will be called when the socket event occurs. Similar to the wsaasyncselect () function,LnetworkeventParameter is a bitwise combination of all
The socket events to monitor. The same event definitions are used for the wsaeventselect () function as for the wsaasyncselect () function. When a socket event occurs,
Event method registered by the wsacreateevent ()
Function is executed.

Overlapped I/O

Possibly one of the greatest features of the Winsock
Interface is the concept of overlapped I/O. This technique allows a program
Post one or more asynchronous I/O requests at a time using a special data
Structure. The data structure (wsaoverlapped) defines
Multiple sockets and event objects that are matched together. The events are
Considered to beOverlapping,In that multiple events can
Be called simultaneously as the sockets receive events.

To use the overlapped technique, a socket must be created with
Wsasocket () function call using the overlapped Enabled
Flag (the socket () function does not include this
Flag). Likewise, all data communication must be done using the wsarecv () and wsasend () functions.
These Winsock functions use an overlapped I/O flag to indicate that the data
Will use the wsaoverlapped data structure.

Although using overlapped I/O can greatly improve performance
Of the network program, it doesn' t solve all of the possible difficulties. One
Specified coming of the overlapped I/O technique is that it can define only 64
Events. For large-scale network applications that require hundreds
Connections, this technique will not work.

Completion Ports

Another downside to the overlapped I/O technique is that all
Of the events are processed within a single thread in the program. To allow
Events to be split among threads, Windows introducedCompletion port. A completion port allows the programmer
Specify a number of threads for use within a program, and assign events to
Individual threads. By combining the overlapped I/O technique with
Completion port method, a programmer can handle overlapped socket events using
Separate program threads. This technique produces really interesting results on
Systems that contain more than one processor. By creating a separate thread
Each processor, multiple sockets can be monitored simultaneously on each
Processor.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.