c中的简单套接字编程

时间:2014-02-10 16:21:12

标签: c sockets

我正在编写一个简单的套接字编程。

        //  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。 并且服务器不显示板。我没错。 看起来一切都还好。

我已经找到了这个简单编程的两天时间。

帮帮我。

非常感谢!!真!!

1 个答案:

答案 0 :(得分:0)

这里有一个适合多个用户的代码:

#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;
}

这取自我与大学中的一些合作伙伴所做的操作系统工作。我希望它有所帮助!