socket, the server and the client dialogue

server:

_CRT_SECURE_NO_WARNINGS #define
#include <stdio.h>
#include <String>
#include <winsock2.h> // Net Library version 2.2 with the current system of the highest version
#pragma comment (lib, "Ws2_32.lib" ) // Load dynamic Link library x32.x64 are using a version of this ws2_32.lib
// above for the second edition of the first edition of the header file is WinSock.h dynamic library wsock32.lib
a using namespace std;


main int ()
{
/ * If the call library version 2.1 Error direct assignment (WORD to short integers, floating point 2.1)
using the macro to store, to the memory MAKEWORD (2,1) is converted to 2 258 is a binary 000100000010
upcoming major version number 2, bits stored in the low byte (8 bits 1 byte), a minor version number, stored in the high byte 0001 <because the head is stored in high memory first data> * /
WORD m_versions = MAKEWORD (2,2 &); // MAKEWORD (a, B) is the minor version number parameter 1, parameter 2 is the major version number
WSADATA m_data; // socket for receiving the information returned by

// *** *** 1 Open Network Library
int answer = WSAStartup (m_versions, & m_data); // parse parameter 21 is the highest we want to use version 2 to version 3 system can provide information for the current library 4 results current socket or open state

if (answer = 0!) // open failure results
{
Switch (answer)
{
Case WSASYSNOTREADY:
the printf; ( "dependent network traffic network subsystem is not ready.")
BREAK;
WSAVERNOTSUPPORTED Case:
printf ( "The current system does not support the required library version.");
BREAK;
Case WSAEINVAL:
printf ( "unable to find the current version of the required library DLL.");
BREAK;
Case WSAEPROCLIM:
printf ( "current number of ports has been up limit ");.
BREAK;
Case the WSAEINPROGRESS:
the printf (" current initialization functions are blocked ");.
BREAK;
Case WSAEFAULT the:
the printf (" current pointer (parameter 2) for the invalid pointer ");.
BREAK;
}
}
if (m_data.wVersion! = 514) // version 2.2 i.e. 2.2 failed to open version that is stored in a single byte decimal 514
{//HIBYTE(m_data.wVersion) obtaining the high byte of the member (i.e., the high version number ) LOBYTE () Gets the low byte of the member
WSACleanup (); // the specified version failed to open, turning off the network library
System ( "PAUSE");
return 0;
}

 


*** 2 *** // create server socket for each return value is the total number of unique values TCP / IP protocol returns, representing the characteristics of each protocol.
SOCKET m_ServerSocket = socket (AF_INET, SOCK_STREAM , IPPROTO_TCP); // MFC similar window handle, the port operations need to use the value of the socket
// Address Parameter Type 1 (IPV4 form), the socket type 2 (sequential, reliable, bi-directional, connection-based byte stream), 3 types of protocols (TCP protocol parameter corresponds. 1)

IF (== INVALID_SOCKET is m_ServerSocket) // creation failed
{
int m_ErrorNum the WSAGetLastError = ();
the printf ( "Create server socket failed, error code:% D \ n-", m_ErrorNum);
WSACleanup (); // the specified version failed to open, turning off the network library
System (" PAUSE ");
return 0;
}

 

sockaddr_in m_ServerSocketaddr; // structure, the type of the memory address, and the address port (as the sockaddr_in and sockaddr structure, but the former is easy assignment, which is passed as a parameter easy)
m_ServerSocketaddr.sin_family = AF_INET; // the address of the same type when creating
m_ServerSocketaddr .sin_addr.S_un.S_addr = inet_addr ( "127.0.0.1") ; // convert the string to an IP address is stored, 127.0.0.1 is the loopback address (no PC) tests used locally
m_ServerSocketaddr.sin_port = htons (12345); // port number should be used to convert it to host byte order, and the port number is unique and can not repeat the bind

address @ 3 *** *** corresponding binding (found computer) and port number (found on the specific application)
int = m_bind the bind (m_ServerSocket, (sockaddr *) & m_ServerSocketaddr, sizeof (m_ServerSocketaddr));
IF (! m_bind = 0) // creation failed
{
int m_ErrorNum = WSAGetLastError ();
printf ( "bind failed, error code:% D \ n-", m_ErrorNum);
the closesocket (m_ServerSocket);
WSACleanup ();
System (" PAUSE ");
return 0;
}

*** 4 *** // start the listener, listen for client connections (similar to starting the server so that clients can connect)
int = m_listen the listen (m_ServerSocket, 5); // server sockt. The maximum length of the queue of pending connections (assuming that the server can process simultaneously 5, 8 come in now, the remaining queued for processing) the SOMAXCONN allow the system to choose their own proper number
if (m_listen! = 0) // failed to start
{
m_ErrorNum the WSAGetLastError = int ();
the printf ( "failed to start, error code:% D \ n-", m_ErrorNum);
the closesocket (m_ServerSocket);
WSACleanup ();
System ( "PAUSE");
return 0;
}

 

sockaddr_in m_ClientSocketaddr; 3 // consistent with the step, the structure of the client data store
int m_ClientLen = sizeof (m_ClientSocketaddr); // Size structure

5 *** // *** accepting connections. When there is a client connects, the server to create a socket, for maintaining a communication parameter 2.3 may be set to NULL not give the client information.
SOCKET m_ClientSocket = Accept (m_ServerSocket, (the sockaddr *) & m_ClientSocketaddr, & m_ClientLen);
// accept function has been in a blocked state (waiting for connection), does not execute down and can only link a multiple client connections you need to cycle, and corresponds to the number of (otherwise have been blocked)

IF (m_ClientSocket == INVALID_SOCKET) // returns the invalid Socket
{
int m_ErrorNum the WSAGetLastError = ();
the printf ( "client connection fails, error code:% D \ n-", m_ErrorNum);
the closesocket (m_ServerSocket);
WSACleanup ();
System ( "PAUSE") ;
return 0;
}
the printf ( "successful client connection \ n");

int a = 5;
while (a!=0,a--)
{

// 6 *** *** receiving data sent by the client
char StoCbuf [1500] = {0 }; // for storing client to server accepts character
int A = the sizeof (StoCbuf);
int = m_ClientStrLen the recv (m_ClientSocket, StoCbuf, sizeof (StoCbuf ), 0); // 1 sockt from accepting what is, which is stored in, put the number of read mode (0 is the default) will always be in the blocked state, until the client its operation
if (m_ClientStrLen == 0) // i.e. the client is offline
{
the printf ( "connection is interrupted, the client is offline");
}
the else IF (m_ClientStrLen of SOCKET_ERROR is ==)
{
int m_ErrorNum the WSAGetLastError = ();
the printf ( " data receiving client failed, error code:% D \ n-", m_ErrorNum);
BREAK;
}
the else
{
the printf (" client:% S \ n-", StoCbuf);
}


*** *** 7 // send data to the client
printf ( "Server:");
the gets (StoCbuf);
int m_ServerStrLen = Send (m_ClientSocket, StoCbuf, strlen (StoCbuf), 0); // object of the socket, the transmission data length of transmission data, transmission mode
IF (m_ServerStrLen of SOCKET_ERROR is ==)
{
int m_ErrorNum the WSAGetLastError = ();
the printf ( "server fails to send data, error code:% D \ n-", m_ErrorNum);
}
IF (= StoCbuf = "886")
BREAK;
}


// After use, first destroy the created socket (the function is a function of the network inside the library), and then close the network library
closesocket (m_ServerSocket);
WSACleanup ();

system("pause");
}

 

 

 

Client:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")

main int ()
{
/ * open a network library * /
WORD m_versions MAKEWORD = (2, 2); // MAKEWORD (A, B) is the minor version number parameter 1, parameter 2 is the major version number
WSADATA m_data; // with receiving the information returned to the socket
int answer = WSAStartup (m_versions, & M_DATA);
IF (answer = 0!) result of the failure to open //
{
Switch (answer)
{
Case WSASYSNOTREADY:
the printf ( "dependent network traffic network subsystem has not ready ");.
BREAK;
Case WSAVERNOTSUPPORTED:
printf (" system does not support the current version of the required library ");.
BREAK;
Case WSAEINVAL:
printf (" unable to find the required DLL library current version ");.
BREAK;
Case WSAEPROCLIM :
printf ( "current number of ports has reached the limit.");
BREAK;
Case WSAEINPROGRESS:
printf ( "current initialization function is blocked.");
BREAK;
Case WSAEFAULT:
printf ( "current pointer (parameter 2) for the invalid pointer.");
BREAK;
}
return 0;
}
IF (! m_data.wVersion = 514) failed to open // i.e. 2.2 to 2.2 that is stored in a single byte decimal the 514
{//HIBYTE(m_data.wVersion) obtaining the high byte of the member (i.e., a higher version number) LOBYTE () Gets the low byte of the member
WSACleanup (); // open the specified version fails, the network is turned off library
System ( "PAUSE");
return 0;
}

/ * 2 * creation server Socket /
SOCKET m_ServerSocket = Socket (AF_INET, SOCK_STREAM, IPPROTO_TCP go); // window handle is similar to the MFC, the port operations need to use the socket value
// address parameter type 1 (IPV4 form), socket type 2 (sequential, reliable, bi-directional, connection-based byte stream), 3 types of protocols (TCP protocol parameters corresponding to 1)

if (m_ServerSocket == INVALID_SOCKET) // creation failed
{
int m_ErrorNum = WSAGetLastError ();
printf ( "to create a server socket failed with error code:% d \ the n-", m_ErrorNum);
WSACleanup (); // could not open the specified version , then turn off the network library
System ( "PAUSE");
return 0;
}

/ * 3 are connected to the server * /
the sockaddr_in m_ServerMsg; // server load information
m_ServerMsg.sin_family = AF_INET; // address type
m_ServerMsg.sin_addr.S_un.S_addr = inet_addr ( "127.0.0.1") ; // server IP address characters serial form into an IP address is stored, 127.0.0.1 is the loopback address, locally (no PC) tests using
m_ServerMsg.sin_port = htons (12345); // port number of the server is converted to the host network byte order byte sequence
int m_connect = connect (m_ServerSocket, (the sockaddr *) & m_ServerMsg, the sizeof (m_ServerMsg));
IF (m_connect = 0!)
{
int m_ErrorNum = the WSAGetLastError ();
the printf ( "connection to server fails, error code:% d \ n" , m_ErrorNum);
closesocket (m_ServerSocket); // close the socket created;
WSACleanup (); // could not open the specified version of the network library is closed
System ( "PAUSE");
return 0;
}
printf ( "servers were successfully connected \ n ");


the while (. 1)
{
/ * message sent to the server. 4 * /
char CtoSbuf [1500] = {0}; // the client to the server
printf ( "Client:");
the gets (CtoSbuf);
int m_ServerStrLen = Send ( m_ServerSocket, CtoSbuf, strlen (CtoSbuf) , 0); // length purpose socket, data transmission, data transmission, the transmission scheme
IF (m_ServerStrLen of SOCKET_ERROR is ==)
{
int m_ErrorNum the WSAGetLastError = ();
the printf ( "client sends data failed, error code:% D \ n-", m_ErrorNum);
}

/ * Receiving data sent by the server 5 * /
char StoCbuf [1500] = {0}; // for storing character sent from the server
int m_ClientStrLen = recv (m_ServerSocket, StoCbuf , sizeof (StoCbuf), 0); // 1 sockt from accepting what is, which is stored in, put the number of read mode (0 is the default) will always be in the blocked state until the client its operation
if (m_ClientStrLen == 0) // That client is offline
{
printf ( "connection is interrupted, the server closed");
}
the else IF (m_ClientStrLen of SOCKET_ERROR is ==)
{
int m_ErrorNum the WSAGetLastError = ();
printf ( "data receiving client failed, error code:% d \ n", m_ErrorNum );
BREAK;
}
the else
{
the printf ( "server:% S \ n-", StoCbuf);
}
IF (StoCbuf == "886")
{
BREAK;
}
}


closesocket (m_ServerSocket); // close the socket created;
WSACleanup (); // could not open the specified version, then close the Network Library
System ( "PAUSE");
}  

 

First run the server, and then run the client, the following operating results

Guess you like

Origin www.cnblogs.com/aaaguai/p/12052135.html