Basic knowledge of Windows Socket network programming (moderate and low)

Source: Internet
Author: User
Tags set socket

The following describes how to implement the layer-7 network protocol in Windows:

7-layer protocol win System
________________________________________
7 Application Layer 7 ApplicationsProgram
________________________________________________
6 presentation layer 6 Winsock API (DLL)
___________________________________________
5 Session Layer 5 SPI (DLL)
__________________________________________________
4 Transport Layer 4 TDI (VxD, sys)
___________________________________________________
3 network layer 3 NDIS (VxD, sys)
__________________________________________________
2 Data Link Layer 2 NIC Driver (VxD, sys)
___________________________________________
1 Physical Layer 1 Nic
_________________________________________________
I believe this ing chart can help you better understand their corresponding relationships.

TCP protocol

Application protocol http ftp Telnet
Transmission protocol TCP UDP
Internet Protocol IP Address
Physical Layer Protocol Nic

The IP protocol ensures data transmission, and the TCP protocol ensures the quality of data transmission.
The TCP/IP protocol is based on a layer-4 structure: the application layer, the transport layer, the network layer, and the interface layer. Each layer passing through the data during transmission adds a header to the data, where the data is used by the receiver at the same layer, in
The acceptor removes the headers after each layer to ensure consistent data formats.

TCP Header structure:
16-bit source port number 16-bit destination port number
32-bit serial number
___________________________________________________________
32-bit confirmation number
four
header Length + 6 reserved words 6-Digit Sign 16-bit window size
_______________________________________________________________________________
16-bit verification and 16-bit emergency data offset
segment
Data Segment
___________________________________________________________________________________

IP header structure:
4-bit IP version number 4-bit header length 8-bit service type 16-bit total length
___________________________________________________________________________________________
16-digit mark 3-digit mark and offset
__________________________________________________________________________
8-bit survival time 8-bit Protocol 16-bit IP header validation and
_________________________________________________________________________________________
32-bit source IP address
___________________________________________________________________________________________
32-bit destination IP address
________________________________________________________________________________________
TCP header and Data

____________________________________________________________________________
Section 4 server and client Programming

In network programming, Winsock is the most common and fundamental one. Now we will discuss socket programming in windows.

Generally, WinSock programming on the Win32 platform takes the following steps:
Define variables-> get the javasck version-> load the Winsock database-> initialize-> Create a socket-> set socket options-> close the socket> uninstall the Winsock database-> release resources

The following describes how to establish Winsock C/S:

Server Client
________________________________________________
1 initialize WSA 1 initialize WSA
____________________________________________________
2. Create a socket 2. Create a socket
_____________________________________________________
3 bind socket 3 to connect to the server
_____________________________________________________
4. listen on the specified port 4 to send and receive data
_____________________________________________________
5. Accept a connection 5. Disconnect
______________________________________________________-
6. send and receive data
___________________________________________________
7. Disconnect
__________________________________________________

Note that during WinSock programming in VC, You need to introduce the following two library files: Winsock. H (this is the header file of Winsock API. Winsock2 and later support Winsock2, so
You can use winsock2.h); ws2_32.lib (Winsock API to connect to the library file ).
The usage is as follows:
# Include
# Pragma comment (Lib, "ws2_32.lib ")

Attention,InVCIn progressWinSockProgramming,The following two library files must be introduced:: Winsock. H (This isWinsock APIHeader file, Win2kThe above supportWinsock2,So
AvailableWinsock2.h); ws2_32.lib (Winsock APIConnection Library File).
The usage is as follows::
# Include
# Pragma comment (Lib, "ws2_32.lib ")

Next, we use the specificCodeDemonstrate the workflow of servers and clients:

First,CreateWsadataStructure,GenerallyWsadata
Wsadata;

Then,CallWsastartupFunction,This function is used to connect the applicationWinsock. dllThe first call.Where,The first parameter isWinSockVersion Number,The second parameter points
WsadataPointer.This function returnsIntType Value,Check the value to determine whether the initialization is successful..The call format is as follows:: Wsastartup (makeword (2, 2), & wsadata ),Where
Makeword (2, 2)Indicates to useWinsock2Version. WsadataUsed to store information returned by the SystemWinSockInformation.

If (iresuit = wsastartup (makeword (2, 2), & wsadata )! = 0)
{
Printf ("wsastartup failed: % d", getlasterror (); // The returned value is different from0,Initialization failed
Exitprocess ();//Exit Program
}

The application completesSocketAfter the library is used,To callWsacleanupFunction exposureSocketLibrary binding,And release resources.

Note:WsastartupAfter Initialization,You must createSocketStructure to saveSocketHandle.

Next we will createSocket.

First, createM_socketOfSocketHandle,CallSocket ()Function,The function return value is stored inM_socketMedium.We useAf_infe, sock_stream, ipproto_tcp
Three Parameters.The first represents the address family., Af_infeIndicatesTCP/IPFamily,The second parameter indicates the service type.,InWinsock2Medium, SocketThe following three types are supported:;

Sock_stream streaming socket
Sock_dgramDatagram socket
Sock_rawOriginal socket

The third parameter indicates the protocol.:

Ipproto_udp UDP protocol for connectionless datagram socket
Ipproto_tcp TCPProtocol for streaming socket
Ipproto_icmp ICMPProtocol for raw socket

M_socket = socket (af_infe, sock_stream, ipproto_tcp); // createTCPProtocol

Run the following code to check whether the returned value is incorrect::

If (m_scoket = invalid_socket)
{
Prinrf ("error at socket (): % d \ n", getlasterror ());
Wsacleanup (); // release resources
Return;
}
Description,IfSocket ()Call failed,He will returnInvalid_socket.

For the server to accept a connection,He must bind a network address,The following code binds an initializedIPAnd PortSocket.The client uses this
IPAddress and port to connect to the server.

Sockaddr_in service;
Service. sin_family = af_inet; // Internet address family
Service. sin_addr.s_addr = inet_addr ("127.0.0.1 ");//LocalIPAddress
Service. sin_port = htons (27015); // 27015Port to be bound

Next we callBindFunction,SetSocketAndSockaddrPassed in as a parameter,Check for errors.

If (BIND (m_socket, (sockaddr *) & service, sizeof (Service) = socket_error)
{
Printf ("BIND () failed. \ n ");
Closesocket (m_socket );
Return;
}

After binding is complete,The server must establish a listener queue.,To accept client requests. Listen ()Enable the server to enter the listening status,Return if this function is successfully called.0,Otherwise
Socket_error.The Code is as follows::

If (Listen (m_socket, 1) = socket-error)
{
Printf ("error listening on socket. \ n ");
}

Server end call completeListen ()After,If the client callsConnect ()Function,The server must callAccept ().In this way, the server and the client formally complete the communication program
Connection action.

Once the server starts listening,We need to specify a handle to useAccept ()Connections accepted by functions,This handle is used to send and receive data..CreateSocketHandle
Socket acceptsocketThen, the infinite loop is used to check whether a connection is passed in..1. connection requests, Accept ()The function will be called.,And return the handle of the connection..

Printf ("waitong for a client to connect... \ n ");
While (1)
{
Acceptsocket = socket_error;
While (acceptsocket = socket_error)
{
Acceptsocket = accept (m_socket, null, null );
}
}

The following describes the client code.:

Sockaddr_in clientservice;
Clientservice. sin_family = af_inet; // Internet address family
Clientservice. sin_addr.s_addr = inet_addr ("127.0.0.1 ");//LocalIPAddress
Clientservice. sin_port = htons (27015); // 27015Port to be bound

The following callConnect ()Function:

If (connect (m_socket, (sockaddr *) & clientservice, sizeof (clientservice) = socket_error)
{
Printf ("failed to connect. \ n ");
Wsacleanup ();
Return;
} // Clear and exit if the call fails
//The call is successful and Data Reading and Writing continues.

_____________________________________________________________________________________
Here,The basic process for servers and clients has been introduced.,Next we will introduce the data exchange.

Send ():
Int send
{
Socket S, // specify the sender socket
Const char far? * Buf ,//Specifies a buffer that stores the data to be sent by the application.
Int Len ,//Number of data bytes to be sent
Int flags //Generally set0
};
C/SBothSendFunction directionTCPSend data to the other end of the Connection.

Recv ():
Int Recv
{
Socket S, // specify the sender socket
Char far? * Buf ,//Specify a bufferRECCReceived data
Int Len ,//SpecifyBufLength
Int flags //Generally set0

};
C/SRecvFunction slaveTCPThe other end of the connection receives data.

_______________________________________________________________________________________________

The complete program code is provided as follows:,You can compile and run it directly.

First, check the client code.:

# Include
# Include
# Pragma comment (Lib, "ws2_32.lib ")
Void main (){

// InitializationWinsock.
Wsadata;
Int iresult = wsastartup (makeword (2, 2), & wsadata );
If (iresult! = No_error)
Printf ("error at wsastartup () \ n ");

// CreateSocket socket.
Socket Client;
Client = socket (af_inet, sock_stream, ipproto_tcp );

If (client = invalid_socket ){
Printf ("error at socket (): % LD \ n", wsagetlasterror ());
Wsacleanup ();
Return;
}

// Connect to the server.
Sockaddr_in clientservice;

Clientservice. sin_family = af_inet;
Clientservice. sin_addr.s_addr = inet_addr ("127.0.0.1 ");
Clientservice. sin_port = htons (27015 );

If (connect (client, (sockaddr *) & clientservice, sizeof (clientservice) = socket_error ){
Printf ("failed to connect. \ n ");
Wsacleanup ();
Return;
}

// Send and receive data.
Int bytessent;
Int bytesrecv = socket_error;
Char sendbuf [32] = "client: sending data .";
Char recvbuf [32] = "";

Bytessent = Send (client, sendbuf, strlen (sendbuf), 0 );
Printf ("Bytes Sent: % LD \ n", bytessent );

While (bytesrecv = socket_error ){
Bytesrecv = Recv (client, recvbuf, 32, 0 );
If (bytesrecv = 0 | bytesrecv = wsaeconnreset ){
Printf ("Connection closed. \ n ");
Break;
}
If (bytesrecv <0)
Return;
Printf ("Bytes Recv: % LD \ n", bytesrecv );
}

Return;
}

Below is the server code:

# Include
# Include
# Pragma comment (Lib, "ws2_32.lib ")
Void main (){

// Initialization
Wsadata;
Int iresult = wsastartup (makeword (2, 2), & wsadata );
If (iresult! = No_error)
Printf ("error at wsastartup () \ n ");

// CreateSocket
Socket server;
Server = socket (af_inet, sock_stream, ipproto_tcp );

If (Server = invalid_socket ){
Printf ("error at socket (): % LD \ n", wsagetlasterror ());
Wsacleanup ();
Return;
}

// BindSocket
Sockaddr_in service;

Service. sin_family = af_inet;
Service. sin_addr.s_addr = inet_addr ("127.0.0.1 ");
Service. sin_port = htons (27015 );

If (BIND (server, (sockaddr *) & service, sizeof (Service) = socket_error ){
Printf ("BIND () failed. \ n ");
Closesocket (server );
Return;
}

// ListenSocket
If (Listen (server, 1) = socket_error)
Printf ("error listening on socket. \ n ");

// Accept the connection
Socket acceptsocket;

Printf ("waiting for a client to connect... \ n ");
While (1 ){
Acceptsocket = socket_error;
While (acceptsocket = socket_error ){
Acceptsocket = accept (server, null, null );
}
Printf ("Client Connected. \ n ");
Server = acceptsocket;
Break;
}

// Send and accept data
Int bytessent;
Int bytesrecv = socket_error;
Char sendbuf [32] = "server: sending data .";
Char recvbuf [32] = "";

Bytesrecv = Recv (server, recvbuf, 32, 0 );
Printf ("Bytes Recv: % LD \ n", bytesrecv );

Bytessent = Send (server, sendbuf, strlen (sendbuf), 0 );
Printf ("Bytes Sent: % LD \ n", bytessent );

Return;
}
This program only describes the synchronization situation!

Section 5 multi-thread programming

Basic concepts of Multithreading,I will not go into details,It's just one course.Programming LanguageWe should have a basic understanding of multiple processes and threads..Here we will focus on how to implement multithreading..

Generally, the main thread of a program is to create an operating system.,If you want it to create additional threads,YesCreatethread ()Function to complete.The original function form is as follows::

Handle createthread ()
{
Lpsecurity_attributes lpthreadattributes, // pointSecurity_attributesPointer
Size_t dwstacksize ,//Indicates the size of the address space allocated by the thread for its stack. The default value is0
LPTHREAD_START-TOUTINE lpstartaddress ,//Indicates the address of the function where the code is located when the new thread starts to execute. It is the name of the thread function.
Lpvoid lpparameter ,//Is the parameter of the input thread function
DWORD dwcreationflags ,//Specify the additional flag created by the control thread0The thread immediately executes the fetchCreate_suincludedThread Suspension
Lpdword lpthreadld //YesDWORDType address,ReturnsID
}

Thread FunctionsLpparameterMust have the following prototype:

DWORD winapi xxxthreadfun (lpvoid lpparameter)
{
Return (0 );
}

________________________________________________________________________________________
Next we will create a thread:

# Include
# Include
DWORD winapi threadfunc (lpvoid lpparam) // a thread function, which is similar to a common function.
{
Printf ("parameter = % d.", * (DWORD *) lpparam );
Return 0;
}

Void main (void)
{
DWORD dwthreadid, dwthrdparam = 1;
Handle hthread;
Hthread = createthread (null, 0, threadfunc, & dwthrdparam, 0, & dwthreadid );
If (hthread = NULL)
{
Printf ("createthread failed (% d) \ n", getlasterror ());
}
Else
{
_ Getch ();
Closehandle (hthread );
}
}

about thread synchronization , I will not explain it here , Please check your own materials , it may be difficult if you do not check it. . cultivate your own hands-on capabilities .

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.