在上一文檔中咱們已經創建好了一個鏈式結構用於存儲用戶信息,這樣咱們就能夠開始創建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