Linux c++开发-11-Socket TCP编程简单案例

服务端:

#include 
#include 
#include 
#include 
#include 
#include 

#include 


int main(void)
{
       
        //1.socket
        int server_sock = socket(AF_INET, SOCK_STREAM, 0);

        // address
        struct sockaddr_in server_addr;
        server_addr.sin_addr.s_addr = INADDR_ANY;
        server_addr.sin_port = htons(9001);
        server_addr.sin_family = AF_INET; 

        //2.bind
        if ( (bind(server_sock, (struct sockaddr*) &server_addr, sizeof(server_addr))) != 0 )
        {
                fprintf(stderr, "couldn't bind: %s\n", strerror(errno));
                exit(EXIT_FAILURE);

        }

        //3.listen
        if ((listen(server_sock, 10)) != 0){
                fprintf(stderr, "couldn't listen: %s\n", strerror(errno));
                exit(EXIT_FAILURE);
        }

        int client_sock;
        //4.accept
        if( (client_sock = accept(server_sock, NULL, NULL)) == -1 ){
                fprintf(stderr, "couldn't accept: %s\n", strerror(errno));
                exit(EXIT_FAILURE);
        }
        char send_message[255] = "hello i am server";
        send(client_sock, send_message, sizeof(send_message), 0);

        char buf[256];
        recv(client_sock,buf,sizeof(buf),0);

        printf("Server recv:%s\n",buf);

        close(server_sock);
        close(client_sock);

        return 0;
}

客户端:

#include 
#include 
#include 

#include 
#include 
#include 

#include 

#include 

int main(void){
        //1.create sock
        int sock = socket(AF_INET, SOCK_STREAM, 0);
        if(sock < 0){
                fprintf(stderr, "can't create socket because of %s\n", strerror(errno));
                exit(EXIT_FAILURE);
        }

        //create address
        struct sockaddr_in server_addr;
        server_addr.sin_addr.s_addr = INADDR_ANY;
        server_addr.sin_port = htons(9001);
        server_addr.sin_family = AF_INET;

        //connect
        if( (connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr))) == -1  ){
                perror("connect error because of: ");
                close(sock);
                exit(EXIT_FAILURE);

        }

        //create recv buffer and recv
        char recv_buffer[255];
        recv(sock, recv_buffer, sizeof(recv_buffer), 0);

        //print
        printf("printf recv: %s\n", recv_buffer);

        char send_message[255] = "I Love China!";
        send(sock, send_message, sizeof(send_message), 0);

        close(sock);
        return 0;
}

结果:
Linux c++开发-11-Socket TCP编程简单案例_第1张图片

你可能感兴趣的:(Linux,c++,开发,linux,c++,tcp/ip)