程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> socket多人聊天法式C說話版(一)

socket多人聊天法式C說話版(一)

編輯:關於C++

socket多人聊天法式C說話版(一)。本站提示廣大學習愛好者:(socket多人聊天法式C說話版(一))文章只能為提供參考,不一定能成為您想要的結果。以下是socket多人聊天法式C說話版(一)正文


起首,不要平步青雲直接處理多人聊天這個成績,先把成績化簡。
1.多人聊天的焦點成績是辦事器若何標識分歧的客戶端,若何依據客戶真個需求轉發新聞給指定客戶端。
2.多人聊天轉化為C-C聊天,然則不再是直接C-C,而是經由過程server轉發新聞,所以釀成==>C-S-C。
3.server若何許可2個client同時銜接,設置listen函數的第二個參數,最年夜銜接數。
4.server若何標識兩個client,用一個構造體數組來寄存兩個client的信息。
5.server若何轉發新聞給client,很簡略,先吸收到的發送給還沒吸收到的。如圖:


6.server若何治理兩個client的銜接狀況,銜接勝利很簡略,就是accpet勝利後就是銜接勝利了。然則怎樣斷定銜接斷開呢?這個觸及到的select函數的應用,有點龐雜~,所以我就簡略的用了一個send函數發送一個空新聞來斷定能否斷開銜接,這個不嚴謹,輕易出BUG,然則理論起來簡略就應用了它。
7.要用線程來治理吸收新聞、發送新聞、接收要求、治理銜接狀況。

技巧要點:C說話線程函數的應用。

_beginthreadex函數原型

_ACRTIMP uintptr_t __cdecl _beginthreadex
( _In_opt_ void* _Security,//平安屬性,NULL為默許平安屬性
 _In_ unsigned _StackSize,//線程客棧的年夜小。假如為0,則線程客棧年夜小和創立它的線程的雷同。普通用0 
 _In_ _beginthreadex_proc_type _StartAddress, //線程函數的地址
 _In_opt_ void* _ArgList, //傳進線程的函數
 _In_ unsigned _InitFlag, //線程初始狀況,0:立刻運轉;CREATE_SUSPEND:吊掛(假如失事狀況界說為吊掛,就要挪用ResumeThread(HANDLE) 來激活線程的運轉) 
 _Out_opt_ unsigned* _ThrdAddr //用於記載線程ID的地址
 )



例子:

#include <process.h>
#include <stdio.h>

unsigned __stdcall Thread(void* param)
{
  printf("%d\n", *(int*)param); //這裡必需先要強行轉換為int*,否則void* 直接解援用會失足。
  return 0;
}

int main()
{
  int i = 0;
  _beginthreadex(NULL, 0, Thread, &i, 0, NULL);
  return 0;
}


1V1,C-S-C聊天例子:
編寫情況:win10,VS2015

後果圖:

server code:

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

#define SEND_OVER 1             //曾經轉發新聞
#define SEND_YET 0             //還沒轉發新聞

int g_iStatus = SEND_YET;
SOCKET g_ServerSocket = INVALID_SOCKET;   //辦事端套接字
SOCKADDR_IN g_ClientAddr = { 0 };      //客戶端地址
int g_iClientAddrLen = sizeof(g_ClientAddr);
bool g_bCheckConnect = false;        //檢討銜接情形
HANDLE g_hRecv1 = NULL;
HANDLE g_hRecv2 = NULL;
//客戶端信息構造體
typedef struct _Client
{
  SOCKET sClient;   //客戶端套接字
  char buf[128];    //數據緩沖區
  char userName[16];  //客戶端用戶名
  char IP[20];     //客戶端IP
  UINT_PTR flag;    //標志客戶端,用來辨別分歧的客戶端
}Client;

Client g_Client[2] = { 0 };         //創立一個客戶端構造體

//發送數據線程
unsigned __stdcall ThreadSend(void* param)
{
  int ret = 0;
  int flag = *(int*)param;
  SOCKET client = INVALID_SOCKET;         //創立一個暫時套接字來寄存要轉發的客戶端套接字
  char temp[128] = { 0 };             //創立一個暫時的數據緩沖區,用來寄存吸收到的數據
  memcpy(temp, g_Client[!flag].buf, sizeof(temp));
  sprintf(g_Client[flag].buf, "%s: %s", g_Client[!flag].userName, temp);//添加一個用戶名頭

  if (strlen(temp) != 0 && g_iStatus == SEND_YET) //假如數據不為空且還沒轉發則轉發
    ret = send(g_Client[flag].sClient, g_Client[flag].buf, sizeof(g_Client[flag].buf), 0);
  if (ret == SOCKET_ERROR)
    return 1;
  g_iStatus = SEND_OVER;  //轉發勝利後設置狀況為已轉發
  return 0;
}

//接收數據
unsigned __stdcall ThreadRecv(void* param)
{
  SOCKET client = INVALID_SOCKET;
  int flag = 0; 
  if (*(int*)param == g_Client[0].flag)      //斷定是哪一個客戶端發來的新聞
  {
    client = g_Client[0].sClient;
    flag = 0;
  }  
  else if (*(int*)param == g_Client[1].flag)
  {
    client = g_Client[1].sClient;
    flag = 1;
  }
  char temp[128] = { 0 }; //暫時數據緩沖區
  while (1)
  {
    memset(temp, 0, sizeof(temp));
    int ret = recv(client, temp, sizeof(temp), 0); //吸收數據
    if (ret == SOCKET_ERROR)
      continue;
    g_iStatus = SEND_YET;                //設置轉發狀況為未轉發
    flag = client == g_Client[0].sClient ? 1 : 0;    //這個要設置,不然會湧現本身給本身發新聞的BUG
    memcpy(g_Client[!flag].buf, temp, sizeof(g_Client[!flag].buf));
    _beginthreadex(NULL, 0, ThreadSend, &flag, 0, NULL); //開啟一個轉發線程,flag標志著要轉發給哪一個客戶端
    //這裡也能夠是招致CPU應用率上升的緣由。
  }

  return 0;
}

//治理銜接
unsigned __stdcall ThreadManager(void* param)
{
  while (1)
  {
    if (send(g_Client[0].sClient, "", sizeof(""), 0) == SOCKET_ERROR)
    {
      if (g_Client[0].sClient != 0)
      {
        CloseHandle(g_hRecv1); //這裡封閉了線程句柄,然則測試成果斷開連C/S接後CPU依然瘋漲
        CloseHandle(g_hRecv2);
        printf("Disconnect from IP: %s,UserName: %s\n", g_Client[0].IP, g_Client[0].userName);
        closesocket(g_Client[0].sClient);  //這裡簡略的斷定:若發送新聞掉敗,則以為銜接中止(其緣由有多種),封閉該套接字
        g_Client[0] = { 0 };
      }
    }
    if (send(g_Client[1].sClient, "", sizeof(""), 0) == SOCKET_ERROR)
    {
      if (g_Client[1].sClient != 0)
      {
        CloseHandle(g_hRecv1);
        CloseHandle(g_hRecv2);
        printf("Disconnect from IP: %s,UserName: %s\n", g_Client[1].IP, g_Client[1].userName);
        closesocket(g_Client[1].sClient);
        g_Client[1] = { 0 };
      }
    }
    Sleep(2000); //2s檢討一次
  }

  return 0;
}

//接收要求
unsigned __stdcall ThreadAccept(void* param)
{

  int i = 0;
  int temp1 = 0, temp2 = 0;
  _beginthreadex(NULL, 0, ThreadManager, NULL, 0, NULL);
  while (1)
  {
    while (i < 2)
    {
      if (g_Client[i].flag != 0)
      {
        ++i;
        continue;
      }
      //假如有客戶端請求銜接就接收銜接
      if ((g_Client[i].sClient = accept(g_ServerSocket, (SOCKADDR*)&g_ClientAddr, &g_iClientAddrLen)) == INVALID_SOCKET)
      {
        printf("accept failed with error code: %d\n", WSAGetLastError());
        closesocket(g_ServerSocket);
        WSACleanup();
        return -1;
      }
      recv(g_Client[i].sClient, g_Client[i].userName, sizeof(g_Client[i].userName), 0); //吸收用戶名
      printf("Successfuuly got a connection from IP:%s ,Port: %d,UerName: %s\n",
        inet_ntoa(g_ClientAddr.sin_addr), htons(g_ClientAddr.sin_port), g_Client[i].userName);
      memcpy(g_Client[i].IP, inet_ntoa(g_ClientAddr.sin_addr), sizeof(g_Client[i].IP)); //記載客戶端IP
      g_Client[i].flag = g_Client[i].sClient; //分歧的socke有分歧UINT_PTR類型的數字來標識
      i++;
    }
    i = 0;

    if (g_Client[0].flag != 0 && g_Client[1].flag != 0)         //當兩個用戶都銜接上辦事器後才停止新聞轉發
    {
      if (g_Client[0].flag != temp1)   //每次斷開一個銜接後再次連上會新開一個線程,招致cpu應用率上升,所以要關失落舊的
      {
        if (g_hRecv1)         //這裡封閉了線程句柄,然則測試成果斷開連C/S接後CPU依然瘋漲
          CloseHandle(g_hRecv1);
        g_hRecv1 = (HANDLE)_beginthreadex(NULL, 0, ThreadRecv, &g_Client[0].flag, 0, NULL); //開啟2個吸收新聞的線程
      }  
      if (g_Client[1].flag != temp2)
      {
        if (g_hRecv2)
          CloseHandle(g_hRecv2);
        g_hRecv2 = (HANDLE)_beginthreadex(NULL, 0, ThreadRecv, &g_Client[1].flag, 0, NULL);
      }    
    }

    temp1 = g_Client[0].flag; //避免ThreadRecv線程屢次開啟
    temp2 = g_Client[1].flag;

    Sleep(3000);
  }

  return 0;
}

//啟動辦事器
int StartServer()
{
  //寄存套接字信息的構造
  WSADATA wsaData = { 0 };
  SOCKADDR_IN ServerAddr = { 0 };       //辦事端地址
  USHORT uPort = 18000;            //辦事器監聽端口

  //初始化套接字
  if (WSAStartup(MAKEWORD(2, 2), &wsaData))
  {
    printf("WSAStartup failed with error code: %d\n", WSAGetLastError());
    return -1;
  }
  //斷定版本
  if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
  {
    printf("wVersion was not 2.2\n");
    return -1;
  }
  //創立套接字
  g_ServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (g_ServerSocket == INVALID_SOCKET)
  {
    printf("socket failed with error code: %d\n", WSAGetLastError());
    return -1;
  }

  //設置辦事器地址
  ServerAddr.sin_family = AF_INET;//銜接方法
  ServerAddr.sin_port = htons(uPort);//辦事器監聽端口
  ServerAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);//任何客戶端都能銜接這個辦事器

  //綁定辦事器
  if (SOCKET_ERROR == bind(g_ServerSocket, (SOCKADDR*)&ServerAddr, sizeof(ServerAddr)))
  {
    printf("bind failed with error code: %d\n", WSAGetLastError());
    closesocket(g_ServerSocket);
    return -1;
  }
  //設置監聽客戶端銜接數
  if (SOCKET_ERROR == listen(g_ServerSocket, 20000))
  {
    printf("listen failed with error code: %d\n", WSAGetLastError());
    closesocket(g_ServerSocket);
    WSACleanup();
    return -1;
  }

  _beginthreadex(NULL, 0, ThreadAccept, NULL, 0, 0);
  for (int k = 0;k < 100;k++) //讓主線程休眠,不讓它封閉TCP銜接.
    Sleep(10000000);

  //封閉套接字
  for (int j = 0;j < 2;j++)
  {
    if (g_Client[j].sClient != INVALID_SOCKET)
      closesocket(g_Client[j].sClient);
  }
  closesocket(g_ServerSocket);
  WSACleanup();
  return 0;
}

int main()
{
  StartServer(); //啟動辦事器

  return 0;
}

client code:

#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <WinSock2.h>
#include <process.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#pragma comment(lib,"ws2_32.lib")
#define RECV_OVER 1
#define RECV_YET 0
char userName[16] = { 0 };
int iStatus = RECV_YET;
//接收數據
unsigned __stdcall ThreadRecv(void* param)
{
  char buf[128] = { 0 };
  while (1)
  {
    int ret = recv(*(SOCKET*)param, buf, sizeof(buf), 0);
    if (ret == SOCKET_ERROR)
    {
      Sleep(500);
      continue;
    }
    if (strlen(buf) != 0)
    {
      printf("%s\n", buf);
      iStatus = RECV_OVER;
    }
    else
      Sleep(100);  


  }
  return 0;
}

//發送數據
unsigned __stdcall ThreadSend(void* param)
{
  char buf[128] = { 0 };
  int ret = 0;
  while (1)
  {
    int c = getch();
    if(c == 72 || c == 0 || c == 68)//為了顯示雅觀,加一個無回顯的讀取字符函數
      continue;          //getch前往值我是經由試驗得出假如是前往這幾個值,則getch就會主動跳過,詳細我也不懂。
    printf("%s: ", userName);
    gets_s(buf);
    ret = send(*(SOCKET*)param, buf, sizeof(buf), 0);
    if (ret == SOCKET_ERROR)
      return 1;
  }
  return 0;
}

//銜接辦事器
int ConnectServer()
{
  WSADATA wsaData = { 0 };//寄存套接字信息
  SOCKET ClientSocket = INVALID_SOCKET;//客戶端套接字
  SOCKADDR_IN ServerAddr = { 0 };//辦事端地址
  USHORT uPort = 18000;//辦事端端口
             //初始化套接字
  if (WSAStartup(MAKEWORD(2, 2), &wsaData))
  {
    printf("WSAStartup failed with error code: %d\n", WSAGetLastError());
    return -1;
  }
  //斷定套接字版本
  if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
  {
    printf("wVersion was not 2.2\n");
    return -1;
  }
  //創立套接字
  ClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (ClientSocket == INVALID_SOCKET)
  {
    printf("socket failed with error code: %d\n", WSAGetLastError());
    return -1;
  }
  //輸出辦事器IP
  printf("Please input server IP:");
  char IP[32] = { 0 };
  gets_s(IP);
  //設置辦事器地址
  ServerAddr.sin_family = AF_INET;
  ServerAddr.sin_port = htons(uPort);//辦事器端口
  ServerAddr.sin_addr.S_un.S_addr = inet_addr(IP);//辦事器地址

  printf("connecting......\n");
  //銜接辦事器
  if (SOCKET_ERROR == connect(ClientSocket, (SOCKADDR*)&ServerAddr, sizeof(ServerAddr)))
  {
    printf("connect failed with error code: %d\n", WSAGetLastError());
    closesocket(ClientSocket);
    WSACleanup();
    return -1;
  }
  printf("Connecting server successfully IP:%s Port:%d\n",
    IP, htons(ServerAddr.sin_port));
  printf("Please input your UserName: ");
  gets_s(userName);
  send(ClientSocket, userName, sizeof(userName), 0);
  printf("\n\n");
  _beginthreadex(NULL, 0, ThreadRecv, &ClientSocket, 0, NULL); //啟動吸收和發送新聞線程
  _beginthreadex(NULL, 0, ThreadSend, &ClientSocket, 0, NULL);
  for (int k = 0;k < 1000;k++)
    Sleep(10000000);
  closesocket(ClientSocket);
  WSACleanup();
  return 0;
}

int main()
{
  ConnectServer(); //銜接辦事器
  return 0;
}

這法式還有一些BUG,個中最年夜的就是關失落一個銜接後CPU應用率瘋漲,我測試過我想到的能夠,照樣找不到成果~,願望有年夜神懂的告訴一下。

以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved