C language simple hello / hi network chat program

A, TCP / IP protocol communication theory

TCP socket programming may be implemented using communication for TCP / IP protocol based connection, it is divided into the server and client in two parts, the main implementation process as shown below:

(1) connection is established: server calls socket (), bind (), listen () After initialization, call accept () blocking wait state in the listening port, the client calls the socket () after initialization, call connect () issue SYN segment and blocked waiting for the server response, the server responds with a SYN-ACK segment, client after receipt of () returns the connect, while a response ACK segment, () returned from the server receives the accept.

(2) Data Transfer: After establishing a connection, TCP protocol provides full-duplex communications service, but the general process of a client / server program that initiates requests by the client, the passive server processes the request, a question-and-answer approach. Therefore, the server from the accept () return immediately after calling read (), read socket is like reading the same pipe, if no data arrives on the block waiting, then the client calls the write () after sending a request to the server, the server receives from the read () returns, to the client's request is processed, during which the client calls the read () block waiting for the response server, the server calls the write () will deal with the results back to the client, call read again () next request block waiting , after the client receives () returns the read, the next request sent, so the cycle continues.

(3) closes the connection: If the client no more requests, call close () closes the connection, like writing end of the closed pipe, the server's read () returns 0, so that the server knows the client closed the connection also call close () closes the connection. Note that, any party call close (), the two transmission directions connected are closed, the data can not be transmitted. If one calls the shutdown () is connected in a semi-closed state, still receive data sent by the other party.

Second, the function description

(1 ) socket function: In order to perform network input and output, a process must be done first thing is to call the socket function to get a file descriptor.

-----------------------------------------------------------------

 #include <sys/socket.h>

 int socket(int family,int type,int protocol);    

 Returns: A non-negative descriptor is successful -1 --- --- failure

 -----------------------------------------------------------------

 (2 ) connect function : when the establishment of a socket with socket, connect call can specify an address for the remote end of the socket; if the byte stream socket, connect on the use of three-way handshake to establish a connection; if the datagram sets interfaces, Connect the remote local address specified only, without sending any data to it.

-----------------------------------------------------------------

 #include <sys/socket.h>      

  int connect(int sockfd, const struct sockaddr * addr, socklen_t addrlen);  

 Returns: 0 --- 0 --- Success failure

 -----------------------------------------------------------------

(. 3 ) the bind function : assign socket a local IP and protocol port for Internet protocol, the protocol addresses are 32-bit IPv4 address or a combination of 128-bit IPv6 address and 16-bit TCP or UDP port number; if the specified port is 0 , while calling bind kernel will select a temporary port, if you specify a wildcard IP address, the kernel will have to wait until the connection is established before choosing a local IP address.

-------------------------------------------------------------------

#include <sys/socket.h>  

 int bind(int sockfd, const struct sockaddr * server, socklen_t addrlen);

 Returns: 0 --- 0 --- Success failure 

 -------------------------------------------------------------------

(. 4 ) the listen function: the listen only function is called TCP server, its role is to create a sock active set of interface into a passive socket, and waits for connection requests from clients.

-------------------------------------------------------------------

#include <sys/socket.h>

 int listen(int sockfd,int backlog);   

 Returns: 0 --- 0 --- Success failure

 -------------------------------------------------------------------

(5 ) the Accept function : accept a TCP server function call, returning from the head of the queue connection has completed a connection has been completed, if completed connection queue is empty, the process goes to sleep.

-------------------------------------------------------------------

#include <sys/socket.h>         

 int accept(int listenfd, struct sockaddr *client, socklen_t * addrlen);  

  Back: non-negative descriptor is successful -1 --- --- failure

 -------------------------------------------------------------------

 (. 6 ) Write and read functions: When the server and the client connection is established, data can be transmitted, the server and the client read / write operations by respective socket descriptor. Because the socket descriptor is also a file descriptor, a file can be read / write function write () and read () receive and transmit operations.

(I) write () function is used to transmit data.                                                    

-------------------------------------------------------------------

#include <unistd.h>         

 int write(int sockfd, char *buf, int len); 

  Returns: non-negative --- --- failure is successful -1

 ------------------------------------------------------------------- 

 (II) read () function for receiving data.

-------------------------------------------------------------------

#include <unistd.h>         

 int read(int sockfd, char *buf, intlen);  

  Back: non-negative --- --- failure is successful -1

 -------------------------------------------------------------------

Third, the programming steps implement the code, and

"A" server-side

Programming steps:

(1) using WSAStartup () function examines Stack installation

(2) using the socket () function creates the server side communication socket

(3) using the bind () socket with the server address of the function will create bindings

(4) using the listen () function so that the socket is ready to receive a connection request server to prepare

(5) using the accept () function receives the connection request sent from the client by the connect ()

(6) After the connection, using the send () function to send data, or use the recv () function receives data according to the connection request

(7) use of the closesocket () function to close the socket (can first shutdown () function to close the read-write channel)

(8) The last call WSACleanup () function ends Winsock Sockets API

Code:

#include <stdio.h> 
#include   <WINDOWS.H>
 #pragma Comment (lib, "ws2_32.lib") // WSAStartup, WSACleanup SOCKET dynamic library and 
int main () 
{ 
    // . 1 protocol version request 
    WSADATA wsadata; 
    WSAStartup (MAKEWORD ( 2 , 2 ), & WSADATA); // request protocol version 2.2 
    IF (! LOBYTE (wsadata.wVersion) = 2 ! || hibyte (wsadata.wVersion) = 2 ) { 
        the printf ( " request protocol failed \ n " );
         return - 1 ; 
    } 
    // 2 creates a socket
    ServerSocket = SOCKET socket (AF_INET, SOCK_STREAM, IPPROTO_TCP go);
     IF (== of SOCKET_ERROR is serverSocket) { 
        the printf ( " Create socket failed \ n- " ); 
        WSACleanup (); 
        return - 2 ; 
    } 
    the printf ( " create socket success \ n- " ) ;
     // 3 creates a protocol address family 
    SOCKADDR_IN addr = { 0 }; 
    addr.sin_family = AF_INET; // protocol version 
    addr.sin_addr.S_un.S_addr the inet_addr = ( " 192.168.43.3 " ); // with their own IP
    = the htons addr.sin_port ( 10086 ); // 0-65535 and generally about 10,000
     @ 4 binding 
    int R & lt = the bind (serverSocket, (the sockaddr *) & addr, the sizeof addr);
     IF (R & lt == - . 1 ) { 
        the printf ( " bind failed \ n- " ); 
        the closesocket (serverSocket); 
        WSACleanup (); 
        return - 2 ; 
    } 
    the printf ( " success of binding \ n- " );
     // . 5 listener 
    R & lt = the listen (serverSocket, 10 ); // monitor 10 users 
    if(R & lt == - . 1 ) { 
        the printf ( " Listener failed \ n- " ); 
        the closesocket (serverSocket); 
        WSACleanup (); 
        return - 2 ; 
    } 
    the printf ( " Listener success \ n- " );
     // . 6 blocking connection requests from clients end hold column 
    SOCKADDR_IN Caddr = { 0 };
     int len = the sizeof Caddr; 
    SOCKET the clientSocket, = Accept (serverSocket, (the sockaddr *) & Caddr, & len);
     IF (== of SOCKET_ERROR is the clientSocket,) { 
        the printf ( " server is down \ n" );
         // Close Socket 
        the closesocket (serverSocket);
         // Clear protocol information 
        WSACleanup ();
         return - 2 ; 
    } 
    the printf ( " client connection to the server:% S \ n- ' , inet_ntoa (cAddr.sin_addr)); // the IP address of the integer into a string
     @ 7 communication 
    char BUFF [ 1024 ];
     the while ( . 1 ) { 
        R & lt = the recv (the clientSocket,, BUFF, 1023 , NULL);
         IF (R & lt> 0 ) { 
            BUFF [R & lt] =0;//添加'\0'
            printf(">>%s\n", buff);
        }
        send(clientSocket, buf, sizeof(buf), 0);
    }
    return 0;
}

 

"Two" client

Programming steps:

(1) using WSAStartup () function examines Stack installation

(2) using the socket () function to create client socket

(3) using the connect () function is also issued request to establish a connection server (before the call can not bind () port number, is done automatically by the system)

() Function to send data, or recv () after receiving the send function (4) to establish a data connection

Use closesocet () function closes the socket

(5) The last call WSACleanup () function, the end of the Winsock Sockets API

Code:

#include <the iostream> 
#include <winsock2.h> 
#include < String >
 #pragma warning (disable: 4996) 

#include <stdio.h> #include <WINDOWS.H> #pragma Comment (lib, "ws2_32.lib" ) // WSAStartup, WSACleanup SOCKET dynamic library and int main () { // . 1 protocol version request WSADATA WSADATA; WSAStartup (MAKEWORD ( 2 , 2 ), & WSADATA); // request protocol version 2.2 IF (LOBYTE (wsadata.wVersion )! = 2 || hibyte (wsadata.wVersion)! = 2 ) { the printf (" Request protocol error \ n- " ); return - . 1 ; } // 2 creates a socket SOCKET the clientSocket, = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP go); IF (== of SOCKET_ERROR is the clientSocket,) { the printf ( " Create socket failed \ n- " ); WSACleanup (); return - 2 ; } the printf ( " create socket success \ n- " ); // . 3 acquisition protocol address family SOCKADDR_IN addr = { 0 }; addr.sin_family = AF_INET; //Protocol version addr.sin_addr.S_un.S_addr the inet_addr = ( " 192.168.43.3 " ); // with his own the IP addr.sin_port the htons = ( 10086 ); // 0-65535 and generally about 10,000 @ 4 is connected to the server int R & lt = connect (the clientSocket,, (the sockaddr *) & addr, the sizeof addr); IF (R & lt == - . 1 ) { the printf ( " connection to server fails \ n- " ); return - . 1 ; } the printf ( " connected server successfully \ n- " ); // 5 communication char buf[1024]; string str; int i; cin >> str; for (i = 0; i < str.length(); i++) { buf[i] = str[i]; } buf[i] = '\0'; send(clientSocket, buf, sizeof(buf), 0); // 接收数据 recv(clientSocket, buf, sizeof(buf), 0); return 0; }

 

Fourth, operating results

1, before the data transfer to start the server, and then start the client:

After starting the server, the server interface is as follows, this time the client requests a connection or not started.

 

 2, after starting the client, the server connection is successfully established, both the interface as follows:

 

 3, after the connection is established, the chat start character string is transmitted with the following results:

 

 

 Internet chat completion of the experiment

 

 

 

Guess you like

Origin www.cnblogs.com/wenkail/p/12008412.html