Socket Network Programming QuickStart (i) teaches you to write UDP/TCP-based service (client) communication

Source: Internet
Author: User
Tags htons

Because Unix and win sockets are the same, for convenience and popularity, this first introduces Winsock programming.
The difficulty of socket network programming is to understand and use basic functions when getting started, because the structure of these functions is often complex, the parameters are mostly structure, which makes it difficult to remember and understand.
But once we know that these functions include the exact meaning of their parameters, socket network programming becomes less complex. Here do not repeat the detailed meaning of the specific functions, the network has a lot of articles, at the same time I suggest you refer to
MSDN, a better understanding of return values, parameters, and so on.
The following are simple single-threaded instances, please follow the next article.
A
UDP: The Chinese name is the User Datagram Protocol, which is a connectionless transport layer protocol in the OSI Reference Model, which provides a simple and unreliable information transfer service for things, and can also be dropped if the network is in good condition.
UDP Communication Flow:
(The initialization of Winsock: WSAStartup)//windows Special
Server side:
Socket: Setting up sockets
Bind: Publish port (Netstat-an visible Port already published)
Sendto/recv/recvfrom: Sending and receiving data

Client side:
Socket: Setting up sockets
Bind: Publish port (Netstat-an visible Port already published)
Sendto/recv/recvfrom: Sending and receiving data
Other functions are described in comments.

Udp--client#define _crt_secure_no_warnings#include <stdio.h> #include <iostream> #include <string> #include <winsock2.h> #pragma comment (lib, "Ws2_32.lib")//Compiler Settings--link library using namespace std;const int PORT = 8009;int m Ain () {int n; Wsadata wd;n = WSAStartup (Makeword (2, 2), &AMP;WD); if (n) {cout << "WSAStartup function Error!" << endl;return-1;}   Socket sock = socket (af_inet, SOCK_DGRAM, 0); Sock_dgram represents udpif (Invalid_socket = = SOCK) {cout << "SOCKET Setup failed! "<< endl;return-1;}   Sockaddr_in sa = {af_inet}; Randomly assign a port (initialize only one value, let the client assign the port itself) n = bind (sock, (sockaddr*) &sa, sizeof (SA)); if (n = = socket_error) {cout << "bind function failed! "<< endl;cout <<" error code is: "<< wsagetlasterror () << endl;return-1;}   Sockaddr_in SA1 = {af_inet, htons (8009)}; Htons must be used because of the network byte order sa1.sin_addr. S_un. S_ADDR = inet_addr ("192.168.253.1");//Specifies the IP and port number to be sent to Char S[256];while (true) {fflush (stdin); get (s); SendTo (sock, S, Strlen (s), 0, (sockaddr*) &sa1,sizeof (SA1)); Send data}return 0;}

Udp-server#include <cstdio> #include <iostream> #include <string> #include <winsock2.h># pragma comment (lib, "Ws2_32.lib") using namespace Std;const int PORT = 8009;int Main () {int n; Wsadata Wd;n=wsastartup (Makeword (2, 2), &WD); if (n) {cout << "WSAStartup function Error! "<< endl;return-1;} Socket sock = socket (af_inet, sock_dgram,0), if (Invalid_socket = = sock) {cout << "socket setup failed!" << endl;cout < ;< "error code is:" << wsagetlasterror () << endl;return-1;} Sockaddr_in sa = {af_inet, htons (PORT)};n=bind (sock, (sockaddr*) &sa, sizeof (SA)), if (n = = socket_error) {cout << ; "Bind bind Port failed!" "<< endl;cout <<" error code is: "<< wsagetlasterror () << endl;return-1;} Else{cout << "Port published successfully:" << port << Endl;} Char S[256];while (true) {n = recv (sock, S, sizeof (s), 0),//RECV returns the actual number of bytes of copy s[n] = ' cout '; Endl << s <<;} return 0;}


Two
TCP: is a connection-oriented (connection-oriented), reliable, byte-stream-based transport layer (Transport layer) communication protocol.
TCP Communication Flow
(Winsock Initialization: WSAStartup)
Server side:
Socket: Setting up sockets
Bind: Publishing Port
Listen: Start listening
Accept: Accept client connections (like the company's front desk)
Send/recv/recvfrom: Send and receive data (like the company's account manager)

Client side:
Socket: Setting up sockets
Bind: Publishing port (client can not bind or bind port 0)
Connect: Connecting to a server
Send/recv/recvfrom: Send and receive data (like the company's account manager)
General communication process is according to: CS Both sides 1 hair 1 symmetrical, once send and receive shun Chaos software out of control.
(Request answer mode: request/reply)

TCP---server#include <cstdio> #include <iostream> #include <string> #include <winsock2.h># pragma comment (lib, "Ws2_32.lib") using namespace Std;const int PORT = 8009;int Main () {int n; Wsadata Wd;n=wsastartup (Makeword (2, 2), &AMP;WD); if (n) {cout << "WSAStartup function Error! "<< endl;return-1;} Socket sock = socket (af_inet, sock_stream,0), if (Invalid_socket = = sock) {cout << "socket setup failed!" << endl;cout &L t;< "error code is:" << wsagetlasterror () << endl;return-1;} Sockaddr_in sa = {af_inet, htons (PORT)};n=bind (sock, (sockaddr*) &sa, sizeof (SA)), if (n = = socket_error) {cout <&lt ; "Bind bind Port failed!" "<< endl;cout <<" error code is: "<< wsagetlasterror () << endl;return-1;} Else{cout << "Port published successfully:" << port << Endl;} Listen (sock, 5); The second parameter is typically set to 5int nlen = sizeof (SA); SOCKET Socka = Accept (sock, (sockaddr*) &sa, &nlen); will return a new connection socket if (Socka = = invalid_socket) {cout << "accepth function failed! "<< endl;cout <<" wrongThe error is: "<< wsagetlasterror () << endl;return-1;} cout << "Someone connects in:" << Inet_ntoa (SA.SIN_ADDR) << "--" << htons (sa.sin_port) << endl;// Output the IP and port of the connector char s[256];while ((n = recv (Socka, S, sizeof (s)-1, 0)) > 0)//-1 is left with a location {s[n] = ' + '; cout << s &LT   ;< endl;/* char k[256] = "Hello"; if (strcmp (s,k) ==0) cout << "Hello Hello, everyone is OK!" "<< Endl;*/}return 0;}

TCP---client#define _crt_secure_no_warnings#include <stdio.h> #include <iostream> #include <string > #include <winsock2.h> #pragma comment (lib, "Ws2_32.lib") using namespace Std;const int PORT = 8009;int Main () { int n; Wsadata wd;n = WSAStartup (Makeword (2, 2), &AMP;WD); if (n) {cout << "WSAStartup function Error!" << endl;return-1;} Socket sock = socket (af_inet, sock_stream, 0); if (Invalid_socket = = sock) {cout << "Socket setup failed! "<< endl;return-1;}   Sockaddr_in sa = {af_inet}; Randomly assigning a port n = bind (sock, (sockaddr*) &sa, sizeof (SA)); if (n = = socket_error) {cout << bind function failed! "<< endl;cout <<" error code is: "<< wsagetlasterror () << endl;return-1;} Sa.sin_addr. S_un. S_ADDR = inet_addr ("192.168.253.1");//115.200.33.112sa.sin_port = htons (port); n = connect (sock, (sockaddr*) &sa, sizeof (SA)); Specify port to send data if (n = = socket_error) {cout << "connect function failed! "<< endl;cout <<" error code is: "<< wsagetlasterror () << endl;return-1;}Char S[256];while (True) {fflush (stdin); gets (s); Send (sock, S, strlen (s), 0);} return 0;}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Socket Network Programming QuickStart (i) teaches you to write UDP/TCP-based service (client) communication

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.