欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C++实现聊天小程序

程序员文章站 2022-07-06 17:23:17
c++写一个游戏聊天服务器,供大家参考,具体内容如下最近学习网络编程写了个聊天小程序,写个博客记录下自己的代码涉及的技术: c++网络编程 c++多线程 c++ stl 设计原...

c++写一个游戏聊天服务器,供大家参考,具体内容如下

最近学习网络编程写了个聊天小程序,写个博客记录下自己的代码

涉及的技术:

  • c++网络编程
  • c++多线程
  • c++ stl

设计原理

以一个结构体的形式存储客户端,用vector存取存在的客户端,开启多线程处理逻辑

服务器允许登陆多个客户端,允许公屏聊天也允许私聊,默认情况下属于公屏聊天,若想私聊,格式为“@用户名+要发送的消息”;运行效果如下图:

C++实现聊天小程序

服务器实现

#include "stdafx.h"
#include <iostream>  
#include "windows.h" //一定要包含该头文件
#include "process.h"
#include <string>
#include <vector>
#include <algorithm>

using namespace std;
#pragma comment(lib, "ws2_32.lib")  //显示加载 ws2_32.dll ws2_32.dll就是最新socket版本

int g_curplayernum = 0; //当前连接数
const char*g_playername[] =  //假定的聊天者名字
{
 "aaaa",
 "bbbb",
 "cccc",
 "dddd",
};

struct playerinfo //利用结构存储连接的客户端
{
 socket sock;
 string name;
};

vector<playerinfo>g_clientsocklist;  //利用vector存取已连接的客户端

void process(void*param)
{
 int index = *(int*)param; //当前子线程编号
 while (1)
 {
  //服务器接收信息
  //int index = *(int*)param;
  char buf[2048] = { 0 };  //接收缓冲区
  int bytes;
  if ((bytes = recv(g_clientsocklist[index].sock, buf, sizeof(buf), 0)) == socket_error)
  {
   cout << "服务器接收数据失败!" << endl;
  }
  //服务器转发(含逻辑处理)
  if (buf[0] == '@')
  {
   //私聊
   string buf(buf);
   string recvplayername = buf.substr(1, 4); //分离出接收者名字
   copy(g_clientsocklist[index].name.begin(), g_clientsocklist[index].name.end(), &buf[1]);

   for (vector<playerinfo>::iterator it = g_clientsocklist.begin(); it != g_clientsocklist.end(); it++)
   {
    if (it->name == recvplayername)
    {
     if (send(it->sock, buf, strlen(buf), 0) == socket_error)
     {
      cout << "发送数据失败 to" << it->name << endl;
     }
     break;
    }
   }
  }
  else
   //群聊
   cout << g_clientsocklist[index].name << "对" << "所有人说:" << buf << endl;
 }
}

int main()
{
 cout << "-----------聊天室服务器-----------" << endl;

 //套接字初始化
 wsadata wsadata; //这个结构被用来存储被wsastartup函数调用后返回的 windows sockets 数据。
 word sockversion = makeword(2, 2); //windows网络编程库的版本号信息
 if (wsastartup(sockversion, &wsadata) != 0) //wsastartup函数是在程序中初始化并加载windows网络
 {
  cout << "套接字初始化失败!" << endl;
  return 0;
 }

 //创建服务器套接字
 socket seversocket;
 if ((seversocket = socket(af_inet, sock_stream, 0)) == socket_error)
 {
  cout << "套接字创建失败!" << endl;
  return 0;
 }
 struct sockaddr_in severaddress;  //一个绑定地址:有ip地址,有端口号,有协议族
 memset(&severaddress, 0, sizeof(sockaddr_in)); //初始化结构体
 severaddress.sin_family = af_inet;
 severaddress.sin_addr.s_un.s_addr = htonl(inaddr_any);//填入本机ip地址 
 severaddress.sin_port = htons(60000);//设定端口号

 //绑定套接字     指定绑定的ip地址和端口号
 if (bind(seversocket, (sockaddr*)&severaddress, sizeof(severaddress)) == socket_error)
 {
  cout << "套接字绑定失败!"<<endl;
  return 0;
 }

 //服务器监听 
 if (listen(seversocket, somaxconn) == socket_error) //监听的第二个参数就是:能存放多少个客户端请求,到并发编程的时候很有用
 {
  cout << "监听失败!" << endl;
  return 0;
 }
 else
  cout << "服务器等待连接......" << endl;


 while (1)
 {
  //服务器接受连接请求
  sockaddr_in revclientaddress; //套接字的地址,端口
  socket revclientsocket = invalid_socket;  //用来接收客户端连接
  //memset(&revclientaddress, 0, sizeof(revclientaddress));
  int addlen = sizeof(revclientaddress);
  if ((revclientsocket = accept(seversocket, (sockaddr*)&revclientaddress, &addlen)) == invalid_socket)
  {
   cout << "接受客户端连接失败!" << endl;
   return 0;
  }
  
  playerinfo stplayerinfo;
  stplayerinfo.sock = revclientsocket;
  stplayerinfo.name = g_playername[g_curplayernum];
  g_clientsocklist.push_back(stplayerinfo);
  int temp = g_curplayernum;
  _beginthread(process, 0, &temp);  //创建子线程来收发数据
  g_curplayernum++;
  cout << stplayerinfo.name << "上线啦!" << endl;
 }
 return 0;
}

客户端

#include "stdafx.h"
#include "windows.h"
#include "iostream"
#include "process.h"
#include <string>
using namespace std;
#pragma comment(lib, "ws2_32.lib")

void receive(void *param)
{
 string msg;
 while (1)
 {
  //客户端接受来自服务器的数据
  socket clientsocket = *(socket*)(param);
  char  recvbuf[2048] = {};  //接收缓冲区
  if (recv(clientsocket, recvbuf, 2048, 0) == socket_error)
  {
   cout << "数据接受失败" << endl;
  }
  else
  {
   msg = recvbuf;
   char sendplayername[5] = { 0 };
   int len = strlen(recvbuf);  //消息长度
   copy(&recvbuf[1], &recvbuf[5], sendplayername); //分离出名字
   msg = msg.substr(5, len - 5);
   cout << sendplayername << "对你说:" << msg<<endl;
  }
   
 }
}

void send(void *param)
{
 while (1)
 {
  //客户端发送数据给服务器
  socket clientsocket = *(socket*)(param);
  char sendbuf[2048] = {};  //发送缓冲区
  cin.getline(sendbuf, 2048);
  if (send(clientsocket, sendbuf, strlen(sendbuf), 0) == socket_error)
  {
   cout << "发送消息失败!";
  }
  else
   cout << "发送消息成功" << endl;
 }
}

int main()
{
 cout << "-----------个人客户端-----------" << endl;
 wsadata  wsa;
 if (wsastartup(makeword(2, 2), &wsa) != 0)
 {
  cout << "套接字初始化失败!"<<endl;
 }
 socket clientsocket;
 if ((clientsocket = socket(af_inet, sock_stream, 0)) == socket_error)
 {
  cout << "套接字创建失败!"<<endl;
 }
 sleep(30);
 struct sockaddr_in clientaddress;  //一个绑定地址:有ip地址,有端口号,有协议族
 memset(&clientaddress, 0, sizeof(sockaddr_in)); //初始化结构体
 clientaddress.sin_family = af_inet;
 clientaddress.sin_addr.s_un.s_addr = htonl(inaddr_any);//填入本机ip地址 
 //clientaddress.sin_port = htons(60001);//设定端口号
 //绑定套接字     指定绑定的ip地址和端口号
 if (bind(clientsocket, (sockaddr*)&clientaddress, sizeof(clientaddress)) == socket_error)
 {
  cout << "套接字绑定失败!" << endl;
  return 0;
 }
 struct sockaddr_in severaddress;  //服务器地址 也就是即将要连接的目标地址
 memset(&severaddress, 0, sizeof(sockaddr_in)); 
 severaddress.sin_family = af_inet;
 severaddress.sin_addr.s_un.s_addr = inet_addr("127.0.0.1");  //127.0.0.1表示本机ip地址
 severaddress.sin_port = htons(60000);//设定端口号

 //开始连接
 if (connect(clientsocket, (sockaddr*)&severaddress, sizeof(severaddress)) == socket_error)
 {
  cout << "客户端:和服务器连接失败!"<<endl;
  return 0;
 }
 else
  cout << "与服务器连接成功!" << endl;

 //创建两个子线程
 _beginthread(receive, 0, &clientsocket);
 _beginthread(send, 0, &clientsocket);

 sleep(infinite); //这里采用另外一种技术避免主线程执行完退出——使其无限期休眠
 // 关闭socket
 if (clientsocket != invalid_socket) {
  closesocket(clientsocket);
  clientsocket = invalid_socket;
 }
    return 0;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。