程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
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