簡體   English   中英

用C語言進行簡單的套接字編程

[英]simple socket programming in c

我正在編程一個簡單的套接字編程。

        //  tictac_server.c
        //  massenger_prac
        //
        //  Created on 2014. 2. 10..
        //

        #include <stdio.h>
        #include <stdlib.h>
        #include <sys/types.h>
        #include <sys/socket.h>
        #include <netinet/in.h>
        #include <netdb.h>
        #include <string.h>
        #include <unistd.h>

        #define PORT 11111

        char my_tic;
        char your_tic;
        int soc;

        char board[4][7] = {{' ','1','|','2','|','3','\0'},{'x',' ','|',' ','|',' ','\0'},
                            {'y',' ','|',' ','|',' ','\0'},{'z',' ','|',' ','|',' ','\0'}};

        //initiallize to server

        int server_init(char *hostname, u_short port){

            struct hostent *myhost;
            struct sockaddr_in serv_addr;
            int s, s_waiting;

            if((myhost = gethostbyname(hostname)) == NULL){

                fprintf(stderr, "wrong host name");
                return -1;
            }

            bzero((char *)&serv_addr, sizeof(serv_addr));
            serv_addr.sin_family = AF_INET;
            serv_addr.sin_port = port;
            bcopy(myhost->h_addr,(char *)&serv_addr.sin_addr,myhost->h_length);

            if((s_waiting = socket(AF_INET, SOCK_STREAM, 0))<0){

                fprintf(stderr, "fail to assign socket");
                return -1;
            }

            if(bind(s_waiting, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == 1){

                fprintf(stderr, "fail to assign port");
                return -1;
            }

            fprintf(stderr, "socket is ready. connecting.......\n");

            listen(s_waiting, 1);
            printf("test1\n");

            s = accept(s_waiting, NULL, NULL);
            printf("test2\n");

            close(s_waiting);
            printf("test3\n");

            return s;
        }


        void show_board(){

            int i;

            for(i=0;i<4;i++){

                printf("%s \n",board[i]);
            }
        }

        int end_game(){

            int i;

            for(i=0;i<4;i++){
                if(board[i][1] == ' ' || board[i][3] == ' ' || board[i][5] == ' ')
                    return 0;
            }

            return 1;
        }

        int win_game(){


            if((board[1][1]=='0')&&(board[1][3]=='0')&&(board[1][5]=='0'))
                return 1;
            if((board[2][1]=='0')&&(board[2][3]=='0')&&(board[2][5]=='0'))
                return 1;
            if((board[3][1]=='0')&&(board[3][3]=='0')&&(board[3][5]=='0'))
                return 1;
            if((board[1][1]=='0')&&(board[2][1]=='0')&&(board[3][1]=='0'))
                return 1;
            if((board[1][3]=='0')&&(board[2][3]=='0')&&(board[3][3]=='0'))
                return 1;
            if((board[1][1]=='0')&&(board[2][3]=='0')&&(board[3][5]=='0'))
                return 1;
            if((board[3][1]=='0')&&(board[2][3]=='0')&&(board[1][5]=='0'))
                return 1;

            return 0;

        }

        int get_your_tic(){

            char recv_data[10];
            int x, y;

            recv(soc, recv_data, 3, 0);

            if(recv_data[0] == 'q'){

                return -1;
            }

            y = recv_data[0] - 'x'+1;
            x = recv_data[1] - '0';

            if(x == 2) x++;
            else if(x == 3) x=x+2;

            board[y][x] = your_tic;

            if(recv_data[2] == '1'){

                printf(" you lose\n");
                show_board();

                return -1;
            }
            return 1;
        }

        int set_my_tic(){

            char send_data[10];
            int x, y;

            while(1){

                gets(send_data);
                if(send_data[0] == 'q'){

                    send(soc,send_data,1,0);
                    return -1;
                }

                if(send_data[0]<'x' || send_data[1] > 'z' || send_data[1] < '1' || send_data[1] > '3'){

                    continue;
                }

                y = send_data[0] - 'x'+1;
                x = send_data[1] - '0';

                if(x==2) x++;
                else if(x==3)
                    x = x+2;

                if(board[y][x] == 'x' || board[y][x] == '0'){

                    printf("you put your zero on the same position\n");
                    continue;
                }

                break;
            }

            board[y][x] = my_tic;

            if(win_game() == 1){

                printf("you win ! \n");

                send_data[2] = '1';
                send(soc, send_data ,3, 0);
                show_board();
                return -1;
            }

            send(soc, send_data, 2, 0);

            return 0;
        }


        void main(){

            char hostname[16];

            my_tic = 'O';
            your_tic = 'X';

            printf("enter the server ip : ");
            gets(hostname);

            if((soc=server_init(hostname, PORT)) == -1){

                exit(1);
            }

            while(1){

                show_board();
                printf("wait....\n");

                if(get_your_tic() == -1){

                    break;
                }

                if(end_game() == 1){

                    printf("draw !! \n");
                    show_board();
                    break;
                }

                show_board();
                printf("it's your turn : q is quit \n");
                if(set_my_tic() == -1){

                    break;
                }


            }

            close(soc);

        }

and 

//
        //  tictac_client.c
        //  massenger_prac
        //
        //  Created on 2014. 2. 10.
        //

        #include <stdio.h>
        #include <stdlib.h>
        #include <sys/types.h>
        #include <sys/socket.h>
        #include <netinet/in.h>
        #include <netdb.h>
        #include <string.h>
        #include <unistd.h>

        #define PORT 11111

        char my_tic;
        char your_tic;

        int soc;

        char board[4][7] = {{' ','1','|','2','|','3','\0'},{'x',' ','|',' ','|',' ','\0'},
            {'y',' ','|',' ','|',' ','\0'},{'z',' ','|',' ','|',' ','\0'}};

        int client_init(char *hostname, u_short port){

            struct hostent *server_host;
            struct sockaddr_in serv_addr;

            int s;

            if((server_host = gethostbyname(hostname)) == NULL){

                fprintf(stderr, "server name is wrong\n");
                return -1;
            }

            bzero((char *)&serv_addr, sizeof(serv_addr));
            serv_addr.sin_family = AF_INET;
            serv_addr.sin_port = port;

            bcopy(server_host->h_addr, (char *)&serv_addr.sin_addr, server_host->h_length);

            if(( s=socket(AF_INET, SOCK_STREAM, 0))<0){

                fprintf(stderr, "fail to assign the socket\n");
                return -1;
            }

            if(bind(s, (struct sockaddr *)&serv_addr, sizeof(server_host)) == 1){

                fprintf(stderr, "fail to connect to server\n");
                return -1;
            }

            fprintf(stderr, "success to connect to server. \n");

            return s;
        }


        void show_board(){

            int i;

            for(i=0;i<4;i++){

                printf("%s \n",board[i]);
            }
        }

        int end_game(){

            int i;

            for(i=0;i<4;i++){
                if(board[i][1] == ' ' || board[i][3] == ' ' || board[i][5] == ' ')
                    return 0;
            }

            return 1;
        }

        int win_game(){


            if((board[1][1]=='0')&&(board[1][3]=='0')&&(board[1][5]=='0'))
                return 1;
            if((board[2][1]=='0')&&(board[2][3]=='0')&&(board[2][5]=='0'))
                return 1;
            if((board[3][1]=='0')&&(board[3][3]=='0')&&(board[3][5]=='0'))
                return 1;
            if((board[1][1]=='0')&&(board[2][1]=='0')&&(board[3][1]=='0'))
                return 1;
            if((board[1][3]=='0')&&(board[2][3]=='0')&&(board[3][3]=='0'))
                return 1;
            if((board[1][1]=='0')&&(board[2][3]=='0')&&(board[3][5]=='0'))
                return 1;
            if((board[3][1]=='0')&&(board[2][3]=='0')&&(board[1][5]=='0'))
                return 1;

            return 0;

        }

        int get_your_tic(){

            char recv_data[10];
            int x, y;

            recv(soc, recv_data, 3, 0);

            if(recv_data[0] == 'q'){

                return -1;
            }

            y = recv_data[0] - 'x'+1;
            x = recv_data[1] - '0';

            if(x == 2) x++;
            else if(x == 3) x=x+2;

            board[y][x] = your_tic;

            if(recv_data[2] == '1'){

                printf(" you lose\n");

                return -1;
            }
            return 1;
        }

        int set_my_tic(){

            char send_data[10];
            int x, y;

            while(1){

                gets(send_data);
                if(send_data[0] == 'q'){

                    send(soc,send_data,1,0);
                    return -1;
                }

                if(send_data[0]<'x' || send_data[1] > 'z' || send_data[1] < '1' || send_data[1] > '3'){

                    continue;
                }

                y = send_data[0] - 'x'+1;
                x = send_data[1] - '0';

                if(x==2) x++;
                else if(x==3)
                    x = x+2;

                if(board[y][x] == 'x' || board[y][x] == '0'){

                    printf("you put your zero on the same position\n");
                    continue;
                }

                break;
            }

            board[y][x] = my_tic;

            if(win_game() == 1){

                printf("you win ! \n");

                send_data[2] = '1';
                send(soc, send_data ,3, 0);
                show_board();
                return -1;
            }

            send(soc, send_data, 2, 0);

            return 0;
        }



        void main(){

            char hostname[16];
            my_tic = 'X';
            your_tic = 'O';

            printf("enter the server's ip : ");
            gets(hostname);

            if((soc = client_init(hostname, PORT)) == -1){

                exit(1);
            }

            while(1){

                show_board();
                printf("now it's your turn : q is quit");

                if(set_my_tic() == -1){

                    break;
                }

                if(end_game() ==1){

                    printf("draw!!! \n");
                    show_board();
                    break;

                }

                show_board();
                printf("wait \n");

                if(get_your_tic() == -1){

                    break;
                }

                if(end_game() == 1){

                    printf("draw!!!!!\n");
                    show_board();
                    break;
                }
            }

            close(soc);

        }

當我執行客戶端文件以及連接服務器時。 發生總線錯誤10.並且服務器未顯示板。 我沒有錯。 看起來一切正常。

我已經為這個簡單的編程找了兩天。

幫我。

非常感謝 !! 真!!

在這里,您有一個適用於多個用戶的代碼:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>

int initializeServer(int port)
{
    int srv_sock;
    struct sockaddr_in srv_addr;
    int yes = 1;

    if ((srv_sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        perror("socket");
        exit(1);
    }

    if (setsockopt(srv_sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
    {
        perror("setsockopt");
        exit(1);
    }

    srv_addr.sin_family = AF_INET;
    srv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    srv_addr.sin_port = htons(puerto);
    memset(&(srv_addr.sin_zero), '\0', 8);

    if (bind(srv_sock, (struct sockaddr *) &srv_addr, sizeof(struct sockaddr_in)) == -1)
    {
        perror("bind");
        exit(1);
    }


    if (listen (srv_sock, BACKLOG) == -1)
    {
        perror("listen");
        exit(1);
    }

    return srv_sock;
}

這是您需要接受客戶端的另一個功能。 您必須在同一個.c文件中找到兩個函數:

int acceptCliente(int srv_sock) //srv_sock is the socket which the multiplexor gives you
{
    int cli_sock;
    struct sockaddr_in cli_addr;
    int sin_zero = sizeof(struct sockaddr_in);

    if ((cli_sock = accept(srv_sock, (struct sockaddr *) &cli_addr, &sin_zero)) == -1)
    {
        perror("accept");
        exit(1);
    }

    return cli_sock;
}

因此,要使用此代碼,您應該鏈接到.h文件,並通過以下方式在您的主函數中調用它:

#include "server.h" //you can name it whatever you want    

#define port 10000 //use any port you want, but it recommended to use over 1024

typedef struct {
            uint32_t size;
            char data[256];
            } __attribute__((packed)) t_data;

int main(int argc, char *argv[])
{
    int srv_sock = initializeServer(port);
    while(1)
    {
        t_data package; //struct to store the info
        bzero(package.data, 256);
        int nbytes = recv(cli_sock, &package, sizeof(t_data), MSG_WAITALL);

        if (nbytes < 0)
        {
        log_error(logger, "Error while receiving the message.");
        exit(1);
        }

        if (nbytes == 0)
        {
            close(cli_sock);
            //cliente disconnected
        }

        if (nbytes > 0)
        {
            //do something with the data =)  
        }
    }       
    return EXIT_SUCCESS;
}

這取自於我與大學中的一些合作伙伴一起進行的OS工作。 希望對您有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM