1. Network Programming Based on TCP

Source: Internet
Author: User

I. Concepts 

1,SocketYes connecting to the applicationProgramBridge with network drivers,SocketCreate in the application and establish a relationship with the driver through the binding operation.

The network architecture is a kind of adhesive that uses different devices and network systems connected with different media to achieve interoperability in different application environments and meet various business needs. The network architecture is a hierarchical method to solve the problem of mutual quality.

Network7Layer:

Application Layer--->Providing network communication services for Applications

Presentation Layer--->Data Representation

Session Layer--->Inter-host communication(Between two application processes)

Transport Layer--->End-to-end connectionIsolates the upper and lower layers of the network so that the network application has nothing to do with the lower layer protocol.

Network Layer--->Find the optimalPath, Forward data packets

Data Link Layer--->Error-free link connection

Physical Layer--->Binary Transfer

2,Port

Is an abstract software structure, including some data structures and I/O buffers. Related to the Agreement.

3,The socket exists in the communication area. A communication region is also called an address family. It is an abstract concept used to combine the common features of processes that communicate through sockets.

To ensure data correctness, the network byte sequence should be set in the network protocol, and the network byte sequence should be unified.

II,Socket Connection Method

1. TCP-based

Server programs:

1) load the socket Library

2) create a socket ).

3) bind the socket to a local address and port (BIND ).

4) set the socket to the listening mode and prepare to receive the client request (Listen ).

5) Wait for the customer's request to arrive. When the request arrives, accept the connection request and return a new socket (accept) corresponding to the connection ).

6) use the returned socket to communicate with the client (send/Recv ).

7) Return, waiting for another customer request.

8) Close the socket.

Client Program:

1) load the socket Library

2) create a socket ).

3) Send a connection request to the server ).

4) Communicate with the server (send/Recv ).

5) Close the socket.

When the server calls the accept function, it will wait and connect.

When the client calls the connect function, it sends a connection request and the Server accepts the request. Then, the two parties establish a connection.

2,Related functions

(1) htonl converts a u_long type from host byte to network byte

(2) htons converts a u_short type from host byte to network byte (2 bytes)

In this structure, wsastartup adds information about the versions it loads to the successful calls to each wsastartup. In the end, wsacleanup should be called to release resources. If the call is successful, the socket descriptor will be returned. If the call fails, invalid_socket is returned. The error message can be returned through wsagetlasterror.

Inet_ntoa: The Windows Sockets inet_ntoa function converts an (IPv4) Internet network address

A string in Internet standard dotted format.

Net_addr: The Windows Sockets inet_addr function converts a string containing an (IPv4) Internet

Protocol dotted address into a proper address for the in_addr structure.

III,Routine:

Server:

# Include <winsock2.h> # include <stdio. h> main () {word wversionrequested; wsadata; wversionrequested = makeword (1, 1); int err = wsastartup (wversionrequested, & wsadata); If (Err! = 0) {return;} If (lobyte (wsadata. wversion )! = 1 | hibyte (wsadata. wversion )! = 1) {wsacleanup (); return;} socket socksrv = socket (af_inet, sock_stream, 0); // if the third parameter is zero, sockaddr_in addrsrv is automatically selected; // define the variable addrsrv of an address struct. sin_addr.s_un.s_addr = htonl (inaddr_any); addrsrv. sin_family = af_inet; addrsrv. sin_port = htons (6000); // htons converts a u_short type from the host's byte order to the network's byte order BIND (socksrv, (sockaddr *) & addrsrv, sizeof (sockaddr )); listen (socksrv, 5); sockaddr_in addrclient; int Len = sizeof (sockaddr); While (1) {socket sock Conn = accept (socksrv, (sockaddr *) & addrclient, & Len); // use this socket to communicate with the client, and the original socket continues to listen. Char sendbuf [100]; sprintf (sendbuf, "Welcome % s to here", inet_ntoa (addrclient. sin_addr); send (sockconn, sendbuf, strlen (sendbuf) + 100); char recvbuf []; Recv (sockconn, recvbuf, 0 ); printf ("% s \ n", recvbuf); closesocket (sockconn) ;}} client: # include <winsock2.h >#include <stdio. h> void main () {word wversionrequested; wsadata; int err; wversionrequested = makeword (1, 1); err = wsastartup (wversionrequested ,& Wsadata); load the socket library if (Err! = 0) {return;} If (lobyte (wsadata. wversion )! = 1 | hibyte (wsadata. wversion )! = 1) {wsacleanup (); return;} socket sockclient = socket (af_inet, sock_stream, 0); Create socket (socket ). Sockaddr_in addrsrv; addrsrv. sin_addr.s_un.s_addr = inet_addr ("127.0.0.1"); addrsrv. sin_family = af_inet; addrsrv. sin_port = htons (6000); Connect (sockclient, (sockaddr *) & addrsrv, sizeof (sockaddr); send a connection request to the server (CONNECT ). Char recvbuf [100]; // communicates with the server (send/Recv ). Recv (sockclient, recvbuf, 100,0); printf ("% s \ n", recvbuf); send (sockclient, "This is me", strlen ("This is me ") + 1, 0); closesocket (sockclient); Disable socket. Wsacleanup (); // This function must be called to clear parameters}
// Socketserver. cpp: defines the entry point of the console application. // # Include "winsock2.h" # include "iostream" # include "ws2tcpip. H "using namespace STD; # pragma comment (Lib," ws2_32.lib ") const int max_request = 1024; const int buf_size = 4096; const char * default_port =" 1000 "; // server int main (INT argc, char * argv []) {wsadata; socket socketforlisten = invalid_socket; socket socketforclient = invalid_socket; struct addrinfo * result = NULL, hints; int iresult; iresult = W Sastartup (makeword (2, 2), & wsadata); If (0! = Iresult) {cout <"wsastartup () failed:" <iresult <Endl; return 1;} sockaddr_in addrserverservice; // address addrserverservice. sin_addr.s_un.s_addr = htonl (inaddr_any); addrserverservice. sin_family = af_inet; addrserverservice. sin_port = htons (1000); zeromemory (& hints, sizeof (hints); hints. ai_family = af_inet; hints. ai_socktype = sock_stream; hints. ai_protocol = ipproto_tcp; hints. ai_flags = ai_passive; I Result = getaddrinfo (null, default_port, & hints, & result); If (0! = Iresult) {cout <"getaddrinfo failed:" <iresult <Endl; wsacleanup (); return 1;} socketforlisten = socket (result-> ai_family, result-> ai_socktype, result-> ai_protocol); If (invalid_socket = socketforlisten) {cout <"socket failed:" <wsagetlasterror () <Endl; freeaddrinfo (result); wsacleanup (); return 1;} iresult = BIND (socketforlisten, result-> ai_addr, (INT) result-> ai_addrlen); If (socket_error = iresult) {cout <"bind failed:" <wsagetlasterror () <Endl; freeaddrinfo (result); closesocket (socketforlisten); wsacleanup (); return 1 ;} cout <"bind" <Endl; freeaddrinfo (result); iresult = listen (socketforlisten, somaxconn); cout <"Start listen... "<Endl; If (iresult = socket_error) {cout <" Listen failed: "<wsagetlasterror () <Endl; closesocket (socketforlisten); wsacleanup (); return 1;} while (1) {cout <"ready to accept:" <Endl; socketforclient = accept (socketforlisten, null, null ); cout <"accept a connection" <Endl; If (invalid_socket = socketforclient) {cout <"Accept failed:" <wsagetlasterror () <Endl; closesocket (socketforlisten); break; // wait for a connection error and exit the loop} // you can create a receiving thread for each connection to send data, enable the server to immediately receive connections from other clients. For example, char * szrecvbuf = NULL; szrecvbuf = new char [max_request]; iresult = Recv (socketforclient, szrecvbuf, max_request, 0 ); if (0 = iresult) // connection has been closed {cout <"connection closing... "<Endl; Delete [] szrecvbuf; closesocket (socketforclient); return 1;} else if (socket_error = iresult) // Recv error, socket error {cout <"Recv failed" <Endl; Delete [] szrecvbuf; closesocket (socketforclient); return 1;} else if (iresult> 0) // received successfully {cout <iresult <"has been reveived:" <szrecvbuf;} closesocket (socketforclient);} return 0 ;}
// Testsocket. cpp: defines the entry point of the console application. // # Include <stdio. h> # include "winsock2.h" # include "iostream" using namespace STD; # define recv_buffer_size 8192 # pragma comment (Lib, "ws2_32.lib") // client int main (INT argc, char * argv []) {wsadata wsadate; // database int iresult = wsastartup (makeword (2, 2), & wsadate); // initiate socket libary. if (iresult! = 0) {cout <"error at wsastartup () \ n";} // If (lobyte (wsadate. wversion )! = 2 | hibyte (wsadata. wversion )! = 2) // {// wsacleanup (); // return 1; //} socket connectsocket; // socketconnectsocket = socket (af_inet, // ipv4sock_stream, // tcp0 ); if (connectsocket = invalid_socket) {cout <"error at socket ():" <wsagetlasterror (); wsacleanup (); return 1 ;} // set the client's protocol, address, portsockaddr_in addrclientservice; // address addrclientservice. sin_family = af_inet; addrclientservice. sin_addr.s_un.s_addr = inet_addr ("127.0.0.1"); addrclientservice. sin_port = htons (1000); char * recvbuf = NULL; // receive bufferint ibytessent; int ibytesrecv = 0; char csendbuf [32] = "get information "; // default data sent if (connect (connectsocket, (sockaddr *) & addrclientservice, sizeof (addrclientservice) = socket_error) {cout <"failed to connect" <Endl; wsacleanup (); return 1;} ibytessent = Send (connectsocket, csendbuf, strlen (csendbuf) + 1, 0); If (ibytessent = socket_error) {cout <"send error" <wsagetlasterror () <Endl; closesocket (connectsocket); return 1 ;} cout <"Bytes Sent:" <ibytessent <Endl; recvbuf = new char [recv_buffer_size]; while (ibytesrecv! = Socket_error) {ibytesrecv = Recv (connectsocket, recvbuf, recv_buffer_size, 0); If (ibytesrecv = 0) {cout <"Connection closed" <Endl; break ;} cout <"Bytes Recv:" <ibytesrecv <Endl;} Delete [] recvbuf; wsacleanup (); Return 0 ;}

Reference

[1] sun Xin's VC ++ in-depth

[2] Very good about socket

Http://www.cnblogs.com/goodcandle/archive/2005/12/10/socket.html#2025579

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.