在上一文档中咱们已经创建好了一个链式结构用于存储用户信息,这样咱们就能够开始创建P2P的服务功能了,首先咱们先建两个基础函数,即注册用户和登陆函数,注册函数是将用户的基本资料进行注册,登陆函数则是将用户信息与链表中的数据进行比较,查找出匹配的用户资料,完成登陆,登陆后前端会获得一个rt_code用户之后就能够使用这个rt_code来进行与服务的交互了。前端
/// <summary>处理用户登陆请求并将登陆结果返回给用户</summary> void doUserLogin(lp_message msg) { //<username>,<userPassword>,<appCode>,<machineCode> char *username = &msg->buff[6]; char *userPassword = strchr(username, ','); userPassword[0] = 0; userPassword += 1; char *appCode = strchr(userPassword, ','); appCode[0] = 0; appCode += 1; char *machineCode = strchr(appCode, ','); machineCode[0] = 0; machineCode += 1; lp_client client = regClient(username, userPassword, appCode, machineCode, msg->addr.sin_addr, msg->addr.sin_port); int addr_len = sizeof(SOCKADDR_IN); if (client == NULL) sendto(hServer, "FAILED", 6, 0, (SOCKADDR*)&msg->addr, addr_len); else { char buff[38]; MoveMemory(buff, "SUCCES", 6); MoveMemory(&buff[6], client->runtimeCode, 32); sendto(hServer, buff, 38, 0, (SOCKADDR*)&msg->addr, addr_len); } } /// <summary>处理用户注册信息</summary> unsigned doRegistUser(lp_message msg) { //<username>,<userPassword>,<appCode>,<machineCode> lp_client client = (lp_client)malloc(sizeof(_client)); memset(client, 0, sizeof(_client)); char *s = msg->buff + 6; char *p = strchr(s, ','); strncpy(client->userName, s, p - s); s = p + 1; p = strchr(s, ','); strncpy(client->userPassword, s, p - s ); s = p + 1; p = strchr(s, ','); strncpy(client->appCode, s, p - s); s = p + 1; strcpy(client->machineCode, s); addClient(client); int addr_len = sizeof(SOCKADDR_IN); if (client == NULL) sendto(hServer, "FAILED", 6, 0, (SOCKADDR*)&msg->addr, addr_len); return 0; }
创建好这两个函数后,咱们就能够将这两个函数放到服务内容中了,即修改receivedMessage函数中的内容,实现根据命令访问这两个函数的功能。app
/// <summary>处理接收到的信息</summary> unsigned WINAPI receivedMessage(void *arg) { lp_message msg = (lp_message)arg; if (strncmp(msg->buff, "REGUSR", 6) == 0)doRegistUser(msg); if (strncmp(msg->buff, "USRLGN", 6) == 0)doUserLogin(msg); printf("Received a [%s] from client %s, string is: %s\n", msg->buff, inet_ntoa(msg->addr.sin_addr), msg->buff); //do anything free(msg); return 0; }
能够看到咱们只是增长了两句话,分别对应msg的前六个字母,即通信的命令名称,这样咱们就能够根据这6个字母的内容找到相应的执行函数了。框架
经过以上这个机制咱们就能够简单实现了P2P的服务响应, 同时创建好了具备良好扩展机制的服务框架。你们能够根据这一模式扩展出适合本身应用的服务函数,同时完成各类应用管理及服务。函数
这样咱们就完成了P2P的服务系统的搭建,用户能够根据本身的需求对这一框架进行调整和补充,完成更加复杂的应用。code