C语言Socket编程基础二------进程通信

这是一个使用C++编写的基于socket的多人聊天应用,包括服务端和客户端代码。服务端能接收多个客户端连接,客户端通过输入账号密码进行登录。存在一个问题:当某个客户端退出时,其他客户端可能会受到影响。用户需要替换服务端的账号文件路径,并且文件内容应按特定格式排列。参考博客介绍了如何构建一个简单的聊天室功能。
摘要由CSDN通过智能技术生成

一、服务端

#include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#pragma comment (lib, "ws2_32.lib")

#define Max_client 8   ///The number of max clients connected.
#define Max_idlength 10 ///The biggest length of user id
#define Max_buff 256
#define Max_name 10
#define Max_pwd 10
#define Max_id 10

SOCKET clientSocket[Max_client];
int login_voucher[Max_client];
char User_id[Max_client][Max_idlength];
int k = 1;
char *account_file = "D:/code/C/socket/basin/file_transmission/account.txt";
char buff[Max_buff];
char user_name[Max_name];

void cleanbuff();
void communication(LPVOID n);
void add_s_n_s(char *s1,int id,char *s2);
void Login(LPVOID n);


int main()
{
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData) != 0;
    if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
    {
        printf("The version of WSADATA is wrong!\n");
        return -1;
    }
    printf("The version of WSADATA is available!\n");
    SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (serverSocket == INVALID_SOCKET)
    {
        printf("Create the Socket unsuccessfully!\n");
        return -1;
    }
    printf("Create the Socket successfully!\n");

    SOCKADDR_IN addr = { 0 };

    addr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(6000);
    int r = bind(serverSocket, (SOCKADDR*)&addr, sizeof(addr));
    if (r == -1)
    {
        printf("Fail to bind!\n" );
        return -1;
    }
    printf("Binded!\n" );

    r = listen(serverSocket, 10);
    if (r == -1)
    {
        printf("Fail to listen!\n" );
        return -1;
    }
    printf("Listened!\n" );
    SOCKADDR_IN cAddr = { 0 };
    int len = sizeof(cAddr);
    int i = 0;
    while (i < Max_client)
    {
        clientSocket[i++] = accept(serverSocket, (SOCKADDR*)&cAddr, &len);
        k++;
        if (clientSocket[i - 1] == SOCKET_ERROR)
        {
            printf("The client is not available!\n");
            closesocket(serverSocket);
            WSACleanup();
            return -1;
        }
        printf("The client %s has connected with server!\n",inet_ntoa(cAddr.sin_addr));
        CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)communication, (LPVOID)i, NULL, NULL);
    }


    return 0;
}

void communication(LPVOID n)
{
    Login(n);
    int r;
    int i = (int)n;
    if(login_voucher[i-1]==1)
    {
        return ;
    }
    cleanbuff();
    strcpy(buff,User_id[i-1]);
    send(clientSocket[i-1],buff,strlen(buff),NULL);
    while (1)
    {
        cleanbuff();
        r = recv(clientSocket[i - 1], buff, Max_buff-1, NULL);
        if (r > 0)
        {
            printf("%s\n",buff);
            for (int j = 0; j < k; j++)
            {
                if(j!=i-1)
                    send(clientSocket[j], buff, strlen(buff), NULL);
            }
        }

    }
}

void Login(LPVOID n)
{
    FILE *fp;
    int read_fp=0;
    int i= (int)n;
    char user_id[Max_id],user_pwd[Max_pwd],user_name[Max_name];
    fp = fopen(account_file,"rb");
    if(fp==NULL)
    {
        printf("The file %s does not exit!",account_file);
        fclose(fp);
        return;
    }
    recv(clientSocket[i-1],buff,Max_buff-1,0);
    printf("The client want to login the account whose ID is %s\n",buff);
    while(1)
    {
        read_fp=fscanf(fp,"%s %s %s",user_id,user_pwd,user_name);
        if(read_fp==-1)
        {
            cleanbuff();
            sprintf(buff,"N");
            send(clientSocket[i-1],buff,strlen(buff),0);
            cleanbuff();
            sprintf(buff,"Can't find the account!");
            send(clientSocket[i-1],buff,strlen(buff),0);
            fclose(fp);
            return 0;
        }
        if(strcmp(user_id,buff)==0)
        {
            cleanbuff();
            sprintf(buff,"Y");
            send(clientSocket[i-1],buff,strlen(buff),0);
            cleanbuff();
            sprintf(buff,"Please input the password of the account!");
            send(clientSocket[i-1],buff,strlen(buff),0);
            fclose(fp);
            break;
        }
    }
    int pwd_time =1;
    while(pwd_time<4)
    {
        cleanbuff();
        recv(clientSocket[i-1],buff,Max_buff-1,0);
        printf("%s\n",buff);
        if (strcmp(buff,user_pwd)==0)
        {
            cleanbuff();
            sprintf(buff,"Y");
            send(clientSocket[i-1],buff,strlen(buff),0);
            cleanbuff();
            sprintf(buff,"Login the account successfully!");
            send(clientSocket[i-1],buff,strlen(buff),0);
            cleanbuff();
            recv(clientSocket[i-1],buff,Max_buff-1,0); ///As a buffer between two transmissions
            printf("%s\n",buff);
            printf("One account has login,ID:%s PWD:%s NAME:%s\n",user_id,user_pwd,user_name);
            cleanbuff();
            strcpy(buff,user_name);
            send(clientSocket[i-1],buff,strlen(buff),0);
            break;
        }
        cleanbuff();
        sprintf(buff,"N");
        send(clientSocket[i-1],buff,strlen(buff),0);
        pwd_time += 1;
        cleanbuff();
        sprintf(buff,"Please input the password again!");
        send(clientSocket[i-1],buff,strlen(buff),0);
    }
    if(pwd_time<4)
    {
        return 1;
    }
    sprintf(buff,"Login the account unsuccessfully!");
    send(clientSocket[i-1],buff,strlen(buff),0);
    return 0;
}
void cleanbuff()
{
    memset(buff,0,Max_buff);
    return ;
}

二、客户端

`

#include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#pragma comment (lib, "ws2_32.lib")

#define Max_buff 256
#define Max_name 10

SOCKET serverSocket;

char buff[Max_buff];
char recvbuff[Max_buff];
char user_name[Max_name];

void cleanbuff();
void recvAndShow();
void scan(char s[],int begin,int len);
int Login();


int main()
{
    char ip_s[100];

    int length1 = 0;
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData) != 0;
    if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
    {
        printf("The version of WSADATA is wrong!\n");
        return -1;
    }
    printf("The version of WSADATA is available!\n");
    serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (serverSocket == INVALID_SOCKET)
    {
        printf("Create the Socket unsuccessfully!\n");
        return -1;
    }
    printf("Create the Socket successfully!\n");
    printf("Please input the IP of Server!\n");
    scanf("%s",ip_s);
    SOCKADDR_IN addr = { 0 };
    addr.sin_addr.S_un.S_addr = inet_addr(ip_s);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(6000);
    int r = connect(serverSocket, (SOCKADDR*)&addr, sizeof(addr));
    if (r == -1)
    {
        printf("It is unsuccessful to connect with the Server!\n");
        return -1;
    }
    printf("It is successful to connect with the Server!\n");
    while(!Login())
        continue;
    CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)recvAndShow, NULL, NULL, NULL);
    fflush(stdin);
    while (1)
    {
        cleanbuff();
        printf("User %s:",user_name);
        sprintf(buff,"User %s:",user_name);
        length1 = strlen(buff);

        scan(buff,length1,Max_buff);
//        printf("buff:%s\n",buff);
//        printf("%d %d\n",length1,strlen(buff));
        if(strlen(buff)!=length1)
            send(serverSocket, buff, strlen(buff), NULL);
    }
    return 0;
}

int Login()
{
    int i=1;
    printf("Login ID:");
    cleanbuff();
    scanf("%s",buff);
    send(serverSocket,buff,strlen(buff),0);
    cleanbuff();
    recv(serverSocket,buff,Max_buff-1,0);
    if(buff[0]=='N')
    {
        cleanbuff();
        recv(serverSocket,buff,Max_buff-1,0);
        printf("%s",buff);
        return 0;
    }
    cleanbuff();
    recv(serverSocket,buff,Max_buff-1,0);
    printf("%s\n",buff);
    while(i<4)
    {
        printf("Login PWD:");
        cleanbuff();
        scanf("%s",buff);
        send(serverSocket,buff,strlen(buff),0);
        recv(serverSocket,buff,Max_buff-1,0);
        if(buff[0]=='Y')
        {
            cleanbuff();
            recv(serverSocket,buff,Max_buff-1,0);
            printf("%s\n",buff);
            cleanbuff();
            sprintf(buff,"I have successfully logged in!"); ///As a buffer between two transmissions
            send(serverSocket,buff,Max_buff-1,0);
            cleanbuff();
            recv(serverSocket,buff,Max_buff-1,0);
            strcpy(user_name,buff);
            return 1;
        }
        cleanbuff();
        recv(serverSocket,buff,Max_buff-1,0);
        printf("%s\n",buff);
    }
    cleanbuff();
    recv(serverSocket,buff,Max_buff-1,0);
    printf("%s\n",buff);
    return 0;
}
void scan(char *s,int begin,int len)
{
    char c;
    int i=begin;
    while(i<len)
    {
        c = getchar();
        if(c =='\n')
            return ;
        s[i++] = c;
    }
    printf("The input is bigger than the length of char array\n");
    return ;
}

void cleanbuff()
{
    memset(buff,0,Max_buff);
    return ;
}

void recvAndShow()
{
    int r, i = 0;
    while (1)
    {
        memset(recvbuff,0,Max_buff);
        r = recv(serverSocket, recvbuff, Max_buff-1, NULL);
        if(r>0)
            printf("%s\n",recvbuff);
    }
}

三、使用方法及存在问题

1、需要替换掉服务端的account_file文件路径,txt内容格式为一行包括:账号名 密码 用户名,例如1 1234 hans。

2、当多个账户聊天时,其中一个退出程序时,将导致其他用户功能异常。

四、参考博客

C++基于socket编程实现聊天室功能

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值