---
# System prepended metadata

title: server

---

# server
```
#include <stdio.h>
#include <winsock.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <sstream>
#define BraodcastPort1 9876
#define BraodcastPort2 9875
#define MAXLINE 1024
using namespace std;

void *ThreadMain(void *arg);
struct ThreadArgs
{
    int clntSock1;
    int clntSock2;
};
//void broadcast(struct sockaddr_in client);

SOCKET	serv_sd;
int   	cli1_len,cli2_len, n,i=1;
char  	str[MAXLINE];
struct 	sockaddr_in   	serv, cli1, cli2;


int main(int argc, char *argv[])

{
    struct ThreadArgs *threadArgs;
    DWORD  threadID;
    int servSock;
    int clntSock1, clntSock2;
    WSADATA wsaData;
    struct sockaddr_in echoServAddr;
    struct sockaddr_in echoClntAddr;
    int clntLen;


    if (WSAStartup(0x101, &wsaData) != 0)
    {
        printf("WSAStartup() failed");
        exit(1);
    }

    serv_sd=socket(AF_INET, SOCK_DGRAM, 0);// 開啟 UDP socket
    BOOL broadcast = TRUE;
    setsockopt(serv_sd, SOL_SOCKET, SO_BROADCAST, ( const char* )&broadcast, sizeof(broadcast)); // 打開廣播功能
    cli1_len = sizeof(cli1);
    //printf("server start broadcasting on port:%d\n",BraodcastPort1);
    cli1.sin_family      = AF_INET;
    cli1.sin_addr.s_addr = inet_addr("255.255.255.255");
    cli1.sin_port        = htons(BraodcastPort1);
    cli2_len = sizeof(cli2);
    //printf("server start broadcasting on port:%d\n",BraodcastPort2);
    cli2.sin_family      = AF_INET;
    cli2.sin_addr.s_addr = inet_addr("255.255.255.255");
    cli2.sin_port        = htons(BraodcastPort2);


    if ((servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
        printf("socket() failed");
    memset(&echoServAddr, 0, sizeof(echoServAddr));
    echoServAddr.sin_family = AF_INET;
    echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    echoServAddr.sin_port = htons(5679);
    if (bind(servSock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
        printf("bind() failed");
    if (listen(servSock, 3) < 0)
        printf("listen() failed");
    printf("Server is waiting for clients.\n");

    for (;;)
    {
        clntLen = sizeof(echoClntAddr);
        if ((clntSock1 = accept(servSock, (struct sockaddr *) &echoClntAddr, &clntLen)) < 0)
            printf("accept() failed");

        if ((clntSock2 = accept(servSock, (struct sockaddr *) &echoClntAddr, &clntLen)) < 0)
            printf("accept() failed");

        threadArgs = (struct ThreadArgs *) malloc(sizeof(struct ThreadArgs));
        threadArgs -> clntSock1 = clntSock1;
        threadArgs -> clntSock2 = clntSock2;
        printf("here\n");

        if (CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) ThreadMain, threadArgs, 0, (LPDWORD) &threadID) == NULL)
            printf("thread_create() failed");

        printf("New chat-room with thread ID: %ld and sockets: %d and %d\n", threadID, clntSock1, clntSock2);
    }

    closesocket(serv_sd);
    WSACleanup();
}

void *ThreadMain(void *threadArgs)
{
    bool newgame=0, newgame1=0, newgame2=0, quit1=0, quit2=0;
    int ans[10];
    char answer[5]="";
    char winmsg1[6]="play1", winmsg2[6]="play2";
    char newg[9]="new game";
    int win=0;

    int clntSock1, clntSock2;
    clntSock1 = ((struct ThreadArgs *) threadArgs) -> clntSock1;
    clntSock2 = ((struct ThreadArgs *) threadArgs) -> clntSock2;

    char echoBuffer[1000];
    int recvMsgSize;

    u_long iMode = 1;
    ioctlsocket(clntSock1, FIONBIO, &iMode);
    ioctlsocket(clntSock2, FIONBIO, &iMode);

    int nError;

    int tmp, p;
    for (int x = 0; x < 10; x++)
    {
        ans[x] = x;
    }
    for (int x = 0 ; x < 4 ; ++x )
    {
        p = rand() % 10 ;
        if ( p == x )
            continue ;
        tmp = ans[x] ;
        ans[x] = ans[p] ;
        ans[p] = tmp ;
    }
    for(int j=0; j<4; j++)
    {
        answer[j]=ans[j]+'0';
    }

    while (1)
    {
        if ((recvMsgSize = recv(clntSock1, echoBuffer, 1000, 0)) > 0)
        {
            printf("1:%s\n",echoBuffer); /*client1 send "new game" or "win"*/
            for(int p=0; p<8; p++)
            {
                if(echoBuffer[p]==newg[p])
                {
                    if(p==7)
                    {
                        newgame1=1;
                        //sendto(serv_sd, answer, strlen(answer), 0,(LPSOCKADDR)&cli1,cli1_len);
                        //printf("send to 1\n");
                    }
                }
                else
                {
                    //printf("1 win\n");
                    win=1;
                    break;
                }
            }
        }
        nError = WSAGetLastError();
        if(nError!=WSAEWOULDBLOCK && nError!=0)
        {
            printf("Player1 disconnected! error code:%d\n", nError);
            break;
        }

        if ((recvMsgSize = recv(clntSock2, echoBuffer, 1000, 0)) > 0)
        {
            printf("2:%s\n",echoBuffer);
            for(int p=0; p<8; p++)
            {
                if(echoBuffer[p]==newg[p])
                {
                    if(p==7)
                    {
                        newgame2=1;
                        //sendto(serv_sd, answer, strlen(answer), 0,(LPSOCKADDR)&cli2,cli2_len);
                        //printf("send to 2");
                    }
                }
                else if(echoBuffer[p]=='2')
                {
                    //printf("2 win\n");
                    win=2;
                    break;
                }
            }
        }
        nError = WSAGetLastError();
        if(nError!=WSAEWOULDBLOCK && nError!=0)
        {
            printf("Player2 disconnected! error code:%d\n", nError);
            break;
        }

        if(newgame1==1&&newgame2==1)
        {
            for (int x = 0 ; x < 4 ; ++x )
            {
                p = rand() % 10 ;
                if ( p == x )
                    continue ;
                tmp = ans[x] ;
                ans[x] = ans[p] ;
                ans[p] = tmp ;
            }
            for(int j=0; j<4; j++)
            {
                answer[j]=ans[j]+'0';
            }
            sendto(serv_sd, answer, strlen(answer), 0,(LPSOCKADDR)&cli1,cli1_len);
            sendto(serv_sd, answer, strlen(answer), 0,(LPSOCKADDR)&cli2,cli2_len);
            printf("answer:%s\n",answer);
            newgame1=0;
            newgame2=0;

        }
        else if(win==1)
        {
            send(clntSock2, winmsg1, strlen(echoBuffer)+1, 0);
            win=0;
        }
        else if(win==2)
        {
            send(clntSock1, winmsg2, strlen(echoBuffer)+1, 0);
            win=0;
        }
    }
    closesocket(clntSock1);
    closesocket(clntSock2);
    free(threadArgs);
    return (NULL);
}
```
# client 1
```
#include <stdio.h>
#include <string.h>
#include <winsock.h>
#include <iostream>
#include <windows.h>

#define BraodcastPort 9876
#define MAXLINE 1024

void *ThreadMain(void *arg);

struct ThreadArgs
{
    SOCKET sd;
};

bool newgame=1; //someone win
bool lose=0;

void SetColor(int color = 7)
{
  HANDLE hConsole;
  hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
  SetConsoleTextAttribute(hConsole,color);
}

int main(int argc, char** argv)
{
    system("mode con cols=80 lines=30  ");

    SOCKET        	sd_b;
    struct sockaddr_in serv_b,cli_b;
    int serv_len;
    char  		ans[1024]="";

    SOCKET        	sd;
    struct sockaddr_in serv;
    char  		str[1024]="\0";
    WSADATA 		wsadata;
    DWORD threadID;
    struct ThreadArgs *threadArgs;
    int n;

    char ng[9]="new game";
    int countA=0;
    int countB=0;
    char win[7]="1 win";
    char wait[5]="wait";
    bool quit=0;

    WSAStartup(0x101,(LPWSADATA) &wsadata);


    sd_b=socket(AF_INET, SOCK_DGRAM, 0);
    BOOL broadcast = TRUE;
    if(	setsockopt(sd_b, SOL_SOCKET, SO_BROADCAST, (const char*)&broadcast, sizeof(broadcast))<0)
        printf("setsockopt() error!\n");
    cli_b.sin_family       = AF_INET;
    cli_b.sin_addr.s_addr  = 0;
    cli_b.sin_port         = htons(BraodcastPort);
    if( bind(sd_b, (LPSOCKADDR) &cli_b, sizeof(cli_b)) <0 )
    {
        printf("bind error!\n");
        system("pause");
        return 0;
    }
    serv_len=sizeof(serv_b);

    sd=socket(AF_INET, SOCK_STREAM, 0);
    threadArgs = (struct ThreadArgs *) malloc(sizeof(struct ThreadArgs));
    threadArgs -> sd = sd;
    serv.sin_family       = AF_INET;
    serv.sin_addr.s_addr  = inet_addr("127.0.0.1");
    serv.sin_port         = htons(5679);
    connect(sd, (LPSOCKADDR) &serv, sizeof(serv));
    if (CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) ThreadMain, threadArgs, 0, (LPDWORD) &threadID) == NULL)
        printf("CreateThread() failed");

    printf(" ? ?????????????? n");
    printf(" ??            ? n");
    printf(" ??  1 A 2 B   ? n");
    printf(" ??            ? n");
    printf(" ? ?????????????? n");
    system("pause");


    while(1)
    {
        SetColor(15);
        if(newgame==1)
        {
            system("cls");
            printf("Input \"new game\" or \"quit\": ");
            gets(str);
            lose=0;
        }
        else
        {
            printf("Your guess: ");
            gets(str);
        }
        if(newgame==1&&lose==0)
        {
            for(int p=0; p<8; p++)
            {
                if(str[p] == ng[p])
                {
                    if(p==7)
                    {
                        n = send(sd, str, strlen(str)+1, 0);
                        if (n < 0)
                        {
                            printf("send error!");
                            //break;
                        }
                        system("cls");
                        printf("wait.");

                        n=recvfrom(sd_b, ans, MAXLINE, 0,(LPSOCKADDR) &serv_b,&serv_len );
                        if(n<=0)
                        {
                            printf("receive error\n");
                        }
                        //printf("%s\n",ans);
                        //printf("client(from:%s):%s\n",inet_ntoa(serv_b.sin_addr),ans);
                        newgame=0;
                        system("cls");
                    }
                }
                else if(str[0]=='q'&&str[1]=='u'&&str[2]=='i'&&str[3]=='t'&&lose==0)
                {
                    printf("Bye~\n");
                    quit=1;
                    system("pause");
                    break;
                }
                else if(lose==0)
                {
                    printf("Wrong input!\nInput \"new game\"!\n");
                    system("pause");
                    break;
                }
            }
        }
        else if(lose==0)
        {
            if(str[0]==str[1]||str[0]==str[2]||str[0]==str[3]
                    ||str[1]==str[2]||str[1]==str[3]||str[2]==str[3])
            {
                printf("Numbers cannot be repeated.\n");
            }
            else
            {
                for(int t=0; t<4; t++)
                {
                    for(int r=0; r<4; r++)
                    {
                        if(ans[t]==str[r])
                        {
                            if(t==r)
                                countA++;
                            else
                                countB++;
                        }
                    }
                }
                if(countA==4)
                {
                    system("cls");
                    SetColor(175);
                    printf("WIN~\n");
                    SetColor(15);
                    newgame=1;
                    n = send(sd, win, strlen(win), 0);
                    if (n < 0)
                    {
                        printf("send error!");
                        //break;
                    }
                    system("pause");
                }
                else
                {
                    printf("%dA%dB\n", countA, countB);
                }
                countA=0;
                countB=0;
            }
        }
        if(quit==1)
        {
            break;
        }
    }
    closesocket(sd_b);
    WSACleanup();
}

void *ThreadMain(void *threadArgs)
{
    SOCKET sd;
    char str[MAXLINE];
    int n;
    char winmsg[10]="";

    sd = ((struct ThreadArgs *) threadArgs) -> sd;
    while(1)
    {
        n = recv(sd, winmsg, MAXLINE, 0);
        if(n<=0)
            break;
        system("cls");
        //printf("recv: %s\n", str);
        SetColor(207);
        printf("Lose\n");
        newgame=1;
        lose=1;
        SetColor(15);
        system("pause");
        //gets(str);
    }
    closesocket(sd);
    WSACleanup();
    return NULL;
}




```
# client 2
```
#include <stdio.h>
#include <string.h>
#include <winsock.h>
#include <iostream>
#include <windows.h>

#define BraodcastPort 9875
#define MAXLINE 1024

void *ThreadMain(void *arg);

struct ThreadArgs
{
    SOCKET sd;
};

bool newgame=1; //someone win
bool lose=0;

void SetColor(int color = 7)
{
  HANDLE hConsole;
  hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
  SetConsoleTextAttribute(hConsole,color);
}

int main(int argc, char** argv)
{
    system("mode con cols=80 lines=30  ");

    SOCKET        	sd_b;
    struct sockaddr_in serv_b,cli_b;
    int serv_len;
    char  		ans[1024]="";

    SOCKET        	sd;
    struct sockaddr_in serv;
    char  		str[1024]="\0";
    WSADATA 		wsadata;
    DWORD threadID;
    struct ThreadArgs *threadArgs;
    int n;

    char ng[9]="new game";
    int countA=0;
    int countB=0;
    char win[7]="2 win";
    char wait[5]="wait";
    bool quit=0;

    WSAStartup(0x101,(LPWSADATA) &wsadata);


    sd_b=socket(AF_INET, SOCK_DGRAM, 0);
    BOOL broadcast = TRUE;
    if(	setsockopt(sd_b, SOL_SOCKET, SO_BROADCAST, (const char*)&broadcast, sizeof(broadcast))<0)
        printf("setsockopt() error!\n");
    cli_b.sin_family       = AF_INET;
    cli_b.sin_addr.s_addr  = 0;
    cli_b.sin_port         = htons(BraodcastPort);
    if( bind(sd_b, (LPSOCKADDR) &cli_b, sizeof(cli_b)) <0 )
    {
        printf("bind error!\n");
        system("pause");
        return 0;
    }
    serv_len=sizeof(serv_b);

    sd=socket(AF_INET, SOCK_STREAM, 0);
    threadArgs = (struct ThreadArgs *) malloc(sizeof(struct ThreadArgs));
    threadArgs -> sd = sd;
    serv.sin_family       = AF_INET;
    serv.sin_addr.s_addr  = inet_addr("127.0.0.1");
    serv.sin_port         = htons(5679);
    connect(sd, (LPSOCKADDR) &serv, sizeof(serv));
    if (CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) ThreadMain, threadArgs, 0, (LPDWORD) &threadID) == NULL)
        printf("CreateThread() failed");

   printf(" ? ?????????????? n");
    printf(" ??            ? n");
    printf(" ??  1 A 2 B   ? n");
    printf(" ??            ? n");
    printf(" ? ?????????????? n");
    system("pause");

    while(1)
    {
        SetColor(15);
        if(newgame==1)
        {
            system("cls");
            printf("Input \"new game\" or \"quit\": ");
            gets(str);
            lose=0;
        }
        else
        {
            printf("Your guess: ");
            gets(str);
        }
        if(newgame==1&&lose==0)
        {
            for(int p=0; p<8; p++)
            {
                if(str[p] == ng[p])
                {
                    if(p==7)
                    {
                        n = send(sd, str, strlen(str)+1, 0);
                        if (n < 0)
                        {
                            printf("send error!");
                            //break;
                        }
                        system("cls");
                        printf("wait.");

                        n=recvfrom(sd_b, ans, MAXLINE, 0,(LPSOCKADDR) &serv_b,&serv_len );
                        if(n<=0)
                        {
                            printf("receive error\n");
                        }
                        printf("%s\n",ans);
                        //printf("client(from:%s):%s\n",inet_ntoa(serv_b.sin_addr),ans);
                        newgame=0;
                        system("cls");
                    }
                }
                else if(str[0]=='q'&&str[1]=='u'&&str[2]=='i'&&str[3]=='t'&&lose==0)
                {
                    printf("Bye~\n");
                    quit=1;
                    system("pause");
                    break;
                }
                else if(lose==0)
                {
                    printf("Wrong input!\nInput \"new game\"!\n");
                    system("pause");
                    break;
                }
            }
        }
        else if(lose==0)
        {
            if(str[0]==str[1]||str[0]==str[2]||str[0]==str[3]
                    ||str[1]==str[2]||str[1]==str[3]||str[2]==str[3])
            {
                printf("Numbers cannot be repeated.\n");
            }
            else
            {
                for(int t=0; t<4; t++)
                {
                    for(int r=0; r<4; r++)
                    {
                        if(ans[t]==str[r])
                        {
                            if(t==r)
                                countA++;
                            else
                                countB++;
                        }
                    }
                }
                if(countA==4)
                {
                    system("cls");
                    SetColor(175);
                    printf("WIN~\n");
                    SetColor(15);
                    newgame=1;
                    n = send(sd, win, strlen(win), 0);
                    if (n < 0)
                    {
                        printf("send error!");
                        //break;
                    }
                    system("pause");
                }
                else
                {
                    printf("%dA%dB\n", countA, countB);
                }
                countA=0;
                countB=0;
            }
        }
        if(quit==1)
        {
            break;
        }
    }
    closesocket(sd_b);
    WSACleanup();
}

void *ThreadMain(void *threadArgs)
{
    SOCKET sd;
    char str[MAXLINE];
    int n;
    char winmsg[10]="";

    sd = ((struct ThreadArgs *) threadArgs) -> sd;
    while(1)
    {
        n = recv(sd, winmsg, MAXLINE, 0);
        if(n<=0)
            break;
        system("cls");
        //printf("recv: %s\n", str);
        SetColor(207);
        printf("Lose\n");
        newgame=1;
        lose=1;
        SetColor(15);
        system("pause");
        //gets(str);
    }
    closesocket(sd);
    WSACleanup();
    return NULL;
}




```



