当前位置:   article > 正文

Winsock套接字开发网络聊天室实例(C/S)模式_基于c/s架构实现多用户的聊天室程序。

基于c/s架构实现多用户的聊天室程序。

聊天室的基本要求

聊天器采用客户端/服务器(C/S)模式;
1,客户端利用UDP与服务器连接,客户端与客户端之间通过UDP互相通讯;
2,服务器端具有服务器端口设置,维护客户端个人信息,记录客户端状态,分配账号等功能
     客户端具有服务器地址及端口设置,用户注册,用户登陆,添加好友和删除好友,查看好友信       息,给好友发送消息等功能;
3,服务器与客户端间、客户端之间的交互采用控制台方式或GUI窗口方式均可;


聊天器实例的实现情况

1,程序完成了基于客户端/服务器(C/S)模式的设计目标,模拟出类似于QQ聊天室的应用方式,并实现其相关的基本功能。
2,程序完成了基于UDP的设计目标,实现了客户端与服务器,客户端与客户端之间通过UDP互相通讯的设计模式。
3,服务器端实现了具有服务器端口设置,维护客户端个人信息,记录客户端状态等应用功能;客户端实现了具有服务器地址及端口设置,用户注册,用户登陆,给好友发送消息,实现多个用户之间群聊等应用功能。
4,不足之处在于服务器与客户端间、客户端之间采用控制台方式实现了相互交互,未实现基于GUI窗口开发的方式。


运行注意事项(看完再去运行蛤)

    这个基于winsock的UDP网络聊天器是本人的期末大作业的内容,因为自己知道做一个课程设计对于很多同学来说难度都太大了,为了让大家能够在更短的时间内有一份可以完整提交的项目以及答辩顺利,所以我无偿的发布出我的大作业供大家学习使用。

项目基于的环境

  • windows操作系统
  • Visual studio 2022 编译器
  • X86(debug)运行架构

网上的项目繁多,所以需要找到适合自己的去学习使用,比如这门课对于苹果电脑的同学就不是很友好。

项目运行须知

同绝大多数的通信实例一样,网络编程对于网络环境的环境&介质要求很高,所以在运行项目之前,请确保运行项目的主机网络的畅通,关闭windows系统的防火墙,连上自己的手机热点做局域网测试效果为佳。

还有要清楚项目的运行逻辑,基于C/S模型的程序实例,一定要记得要先运行服务器,然后在运行客户端,客户端才可以正常访问服务器,并且要注意服务器和客户端的IP与端口信息,这个对于网络通信是非常重要的,很多bug往往不是代码本身的问题,而是出现在了网络配置的问题上,所以如果你是第一在电脑上运行项目,那么第一次就要做好程序在主机上的网络配置,找到代码里有关于网络配置的相关定义进行修改哦。

最后,在用编辑器调试程序运到报错运行不起来时,要学会复制所报出的问题,在百度上搜索问题的答案,这是基本功。


部分实例演示

服务器的运行界面

客户端的运行界面

用户上线提醒

用户注册提醒

 私聊功能的实现

 

群聊功能的实现

 聊天室的整体设计 

该程序采用经典的c/s架构,即采用客户端/服务器架构。模型的设计包括三个主要部分,即文件存储部分,服务器部分,以及客户端部分。

如图3.1.1所示,其中,服务器的功能为接收发送器的消息请求,并根据消息类型进行不同的响应处理;服务器中通过文件存储用户的用户名和密码。

客户端的功能实现包括两个部分:发送器和接收器。其中发送器所实现的功能包括注册新账号,登录已有账号,发送群聊消息和私聊消息等;接收器主要实现的功能包括接收服务器转发的群聊消息和私聊消息,并将其显示在显示屏上。

    服务器要处理的消息类型一共有五种,分别是登录请求、注册请求、群聊消息、私聊消息、退出命令。这五种消息类型,设计使用字符串的第一个字符来进行区分,比如’L‘是Login的首字母,用来作为登录请求的标志,’R‘是Rigister的首字母,用来作为注册请求的标志,’G‘是Group的首字母,用来作为群聊消息的标志,’P'是Personal的首字母,用来作为私聊消息的标志,最后字符串"exit"可以作为用户退出的命令。

 服务器要处理的五种消息类型对应着聊天器所要实现的五种功能,即登录功能,注册功能,群聊功能,私聊功能,关闭程序。下文将针对聊天器所要实现的功能给出设计的方案与实现。

 聊天室服务器完整代码

  1. #include<WinSock2.h>
  2. #include<iostream>
  3. #include<fstream>
  4. #include<vector>
  5. #include<string>
  6. #include<cstdlib>
  7. #pragma comment(lib,"ws2_32.lib")
  8. using namespace std;
  9. #define DEFAULT_PORT 5055
  10. #define BUFFER_LENGTH 1024
  11. class user
  12. {
  13. public:
  14. user(string username, string ip, int sender_port, int receiver_port)
  15. {
  16. this->username = username;
  17. this->ip = ip;
  18. this->sender_port = sender_port;
  19. this->receiver_port = receiver_port;
  20. //设置接收器的地址
  21. receiver.sin_family = AF_INET;
  22. receiver.sin_port = htons(receiver_port);
  23. char *addr = new char[ip.length() + 1];
  24. strcpy(addr, ip.c_str());
  25. receiver.sin_addr.s_addr = inet_addr(addr);
  26. }
  27. string username; //用户名
  28. string ip; //客户端ip地址
  29. int sender_port; //发送器端口
  30. int receiver_port; //接收器端口
  31. struct sockaddr_in receiver; //存储接收器的地址
  32. };
  33. class server
  34. {
  35. public:
  36. bool Startup(); //检测是否满足服务器运行的环境
  37. bool SetServerSocket(); //设置服务器用来监听信息的socket套接字
  38. bool Checktxt(); //检测存储文件是否存在,若不存在,创建一个
  39. void work(); //服务器运行的主函数
  40. void SendMessage(string message, struct sockaddr_in x); //发送信息的函数
  41. void Sendonlinelist(); //向客户端发送好友在线列表
  42. bool TestUsernameAndPassword(string username, string password, int &flag); //测试用户名和密码是否正确
  43. bool TestDuplicateLogin(string username); //测试是否重复登录
  44. bool TestDuplicateRigister(string username); //测试是否重复注册
  45. string Getusername(string ip, int port); //根据ip和端口号获得用户名
  46. int Getuserindex(string username); //根据用户名获得用户在在线用户表的索引号
  47. void extractLoginuserinfor(string userinfor, string &username, string &password, string &receiverport); //提取登录请求中的用户名密码和显示器端口号
  48. void extractRegisteruserinfor(string userinfor, string&username, string&password); //提取注册请求中的用户名和密码
  49. void extactPersonalMessageReceivername(string &message, string &receivername); //提取私聊消息中的接收者的姓名
  50. private:
  51. WSADATA wsaData;
  52. SOCKET sSocket; //用来接收消息的套接字
  53. struct sockaddr_in ser; //服务器地址
  54. struct sockaddr_in cli; //客户地址
  55. int cli_length = sizeof(cli); //客户地址长度
  56. char recv_buf[BUFFER_LENGTH]; //接收数据的缓冲区
  57. vector<user> usertable; //在线用户表
  58. string sendmessage, printmessage; //存储服务器转发、打印用的字符串
  59. int iSend, iRecv; //存储服务器发送和接收的字符串的长度
  60. };
  61. bool server::Startup()
  62. {
  63. if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
  64. {
  65. cout << "Failed to load Winsock." << endl;
  66. return false;
  67. }
  68. return true;
  69. }
  70. bool server::SetServerSocket()
  71. {
  72. //产生服务器端套接口
  73. sSocket = socket(AF_INET, SOCK_DGRAM, 0);
  74. if (sSocket == INVALID_SOCKET)
  75. {
  76. cout << "socket()Failed:" << WSAGetLastError() << endl;
  77. return false;
  78. }
  79. //建立服务器端地址
  80. ser.sin_family = AF_INET;
  81. ser.sin_port = htons(DEFAULT_PORT); //htons()函数把一个双字节主机字节顺序的数转换为网络字节顺序的数
  82. ser.sin_addr.s_addr = htonl(INADDR_ANY); //htonl()函数把一个主机字节顺序的数转换为网络字节顺序的数
  83. if (bind(sSocket, (LPSOCKADDR)&ser, sizeof(ser)) == SOCKET_ERROR)
  84. {
  85. cout << "bind()Failed:" << WSAGetLastError() << endl;
  86. return false;
  87. }
  88. return true;
  89. }
  90. void server::SendMessage(string message, struct sockaddr_in x)
  91. {
  92. char *send_buf = new char[message.length() + 1];
  93. strcpy(send_buf, message.c_str());
  94. SOCKET rSocket = socket(AF_INET, SOCK_DGRAM, 0);
  95. if (rSocket == INVALID_SOCKET)
  96. {
  97. cout << "socket()Failed:" << WSAGetLastError() << endl;
  98. return;
  99. }
  100. iSend = sendto(rSocket, send_buf, message.length() + 1, 0, (SOCKADDR*)&(x), sizeof(x));
  101. if (iSend == SOCKET_ERROR)
  102. {
  103. cout << "sendto failed:" << WSAGetLastError() << endl;
  104. closesocket(rSocket);
  105. return;
  106. }
  107. closesocket(rSocket);
  108. }
  109. void server::Sendonlinelist()
  110. {
  111. string onlinelist;
  112. for (int i = 0; i < usertable.size(); i++)
  113. onlinelist = onlinelist + usertable[i].username + "#";
  114. onlinelist = onlinelist + "$"; //结束标志
  115. SendMessage(onlinelist, cli);
  116. }
  117. bool server::TestUsernameAndPassword(string username, string password, int &flag)
  118. {
  119. if (!Checktxt())
  120. {
  121. cout << "无法找到存储文件." << endl << endl;
  122. flag = 0; //未找到用户名的标志
  123. return false;
  124. }
  125. fstream in("C:\\userform\\userform.txt");
  126. string line;
  127. string username_txt, password_txt;
  128. while (getline(in, line))
  129. {
  130. for (int i = 0; i < line.size(); i++)
  131. {
  132. if (line[i] == '#')
  133. {
  134. username_txt = line.substr(0, i);
  135. password_txt = line.substr(i + 1);
  136. break;
  137. }
  138. }
  139. if (username_txt == username) //该用户名存在
  140. {
  141. if (password == password_txt) //且密码正确
  142. {
  143. in.close();
  144. return true; //返回验证成功
  145. }
  146. cout << "用户" << username << "登录密码错误" << endl << endl; //返回密码错误的信息
  147. flag = 1; //密码错误的标志
  148. return false;
  149. }
  150. }
  151. in.close();
  152. cout << "未注册过的用户:" << username << endl << endl;
  153. flag = 0; //未找到用户名的标志
  154. return false;
  155. }
  156. bool server::TestDuplicateLogin(string username)
  157. {
  158. int i;
  159. for (i = 0; i < usertable.size(); i++)
  160. if (usertable[i].username == username) break;
  161. if (i == usertable.size()) //该用户还没有登录过
  162. return false;
  163. else
  164. {
  165. cout << "用户" << username << "重复登录" << endl;
  166. return true;
  167. }
  168. }
  169. bool server::TestDuplicateRigister(string username)
  170. {
  171. if (!Checktxt())
  172. {
  173. cout << "无法找到存储文件." << endl << endl;
  174. return true;
  175. }
  176. fstream in("C:\\userform\\userform.txt");
  177. string line;
  178. while (getline(in, line))
  179. {
  180. string username_txt;
  181. for (int i = 0; i < line.size(); i++)
  182. {
  183. if (line[i] == '#')
  184. {
  185. username_txt = line.substr(0, i); //提取用户名
  186. if (username_txt == username) //对比,相等则表明已经注册过
  187. {
  188. in.close();
  189. cout << "用户名" << username << "重复注册" << endl << endl;
  190. return true;
  191. }
  192. break; //否则继续对比下一个用户名
  193. }
  194. }
  195. }
  196. in.close();
  197. return false; //代码执行到这说明该用户名还没有注册过
  198. }
  199. string server::Getusername(string ip, int port)
  200. {
  201. for (int i = 0; i < usertable.size(); i++)
  202. if (usertable[i].ip == ip&&usertable[i].sender_port == port)
  203. return usertable[i].username;
  204. cout << "非法的用户连接上服务器" << endl;
  205. cout << "ip地址为:" << ip << endl << "端口号为:" << port << endl;
  206. return "";
  207. }
  208. int server::Getuserindex(string username)
  209. {
  210. int i = 0;
  211. for (i = 0; i < usertable.size(); i++)
  212. if (usertable[i].username == username) break;
  213. return i;
  214. }
  215. void server::extractLoginuserinfor(string userinfor, string &username, string &password, string &receiverport)
  216. {
  217. int i;
  218. for (i = 0; i < userinfor.length(); i++) //提取用户名
  219. {
  220. if (userinfor[i] == '#')
  221. {
  222. username = userinfor.substr(0, i);
  223. break;
  224. }
  225. }
  226. for (int j = i + 1; j < userinfor.length(); j++) //提取密码和显示器端口号
  227. {
  228. if (userinfor[j] == '#')
  229. {
  230. password = userinfor.substr(i + 1, j - i - 1);
  231. receiverport = userinfor.substr(j + 1);
  232. break;
  233. }
  234. }
  235. }
  236. void server::extractRegisteruserinfor(string userinfor, string&username, string&password)
  237. {
  238. for (int i = 0; i < userinfor.size(); i++)
  239. {
  240. if (userinfor[i] == '#')
  241. {
  242. username = userinfor.substr(0, i);
  243. password = userinfor.substr(i + 1);
  244. break;
  245. }
  246. }
  247. }
  248. void server::extactPersonalMessageReceivername(string &message, string &receivername)
  249. {
  250. for (int i = 0; i < message.size(); i++)
  251. {
  252. if (message[i] == '#')
  253. {
  254. receivername = message.substr(0, i);
  255. message = message.substr(i + 1);
  256. break;
  257. }
  258. }
  259. }
  260. bool server::Checktxt()
  261. {
  262. FILE *fp = fopen("C:\\userform\\userform.txt", "r");
  263. if (fp == NULL)
  264. {
  265. system("md C:\\userform");
  266. ofstream out("C:\\userform\\userform.txt");
  267. if (!out)
  268. return false;
  269. out.close();
  270. return true;
  271. }
  272. return true;
  273. }
  274. void server::work()
  275. {
  276. cout << "-----------------" << endl;
  277. cout << "Server running" << endl;
  278. cout << "-----------------" << endl;
  279. while (true) //进入一个无限循环,进行数据接收和发送
  280. {
  281. memset(recv_buf, 0, sizeof(recv_buf)); //初始化接收缓冲区
  282. iRecv = recvfrom(sSocket, recv_buf, BUFFER_LENGTH, 0, (struct sockaddr*)&cli, &cli_length);
  283. if (iRecv == SOCKET_ERROR)
  284. {
  285. cout << "recvfrom()Failed:" << WSAGetLastError() << endl;
  286. continue;
  287. }
  288. //获取发送方的地址(ip和端口)
  289. char *x = inet_ntoa(cli.sin_addr); string address(x); //获取客户端ip
  290. int userport = ntohs(cli.sin_port); //获取客户端端口
  291. string infortype = string(recv_buf); //根据infortype[0]来判断消息的类型
  292. if (infortype[0] == 'L') //登录请求
  293. {
  294. string userinfor = infortype.substr(1); //除去消息类型
  295. string username, password, receiver_port;
  296. extractLoginuserinfor(userinfor, username, password, receiver_port); //提取用户名和密码
  297. //向不合法用户发送登录失败的回应
  298. int flag = 0;
  299. if (!TestUsernameAndPassword(username, password, flag))
  300. {
  301. if (flag == 0)
  302. SendMessage("0", cli);
  303. if (flag == 1)
  304. SendMessage("1", cli);
  305. continue;
  306. }
  307. //查询该用户是否重复登录
  308. if (TestDuplicateLogin(username))
  309. {
  310. SendMessage("2", cli);
  311. continue;
  312. }
  313. //将合法的未登录的用户加入列表
  314. int receiver_port_int = atoi(receiver_port.c_str());
  315. user newuser(username, address, userport, receiver_port_int);
  316. usertable.push_back(newuser);
  317. printmessage = "(上线消息)" + newuser.username + "已上线"; //设置要打印的消息
  318. sendmessage = printmessage; //设置要转发的消息
  319. SendMessage("Y", cli); //向客户端发送登录成功的回应
  320. }
  321. else if (infortype[0] == 'R') //注册信息
  322. {
  323. string userinfor = infortype.substr(1); //除去消息类型
  324. string username, password;
  325. extractRegisteruserinfor(userinfor, username, password); //提取用户名和密码
  326. //检测用户名是否已经注册过
  327. if (TestDuplicateRigister(username))
  328. {
  329. SendMessage("N", cli);
  330. continue;
  331. }
  332. //向文件写入新注册的用户名和密码
  333. if (!Checktxt())
  334. {
  335. SendMessage("N", cli);
  336. continue;
  337. }
  338. fstream out("C:\\userform\\userform.txt", ios::app);
  339. out << userinfor << endl;
  340. out.close();
  341. //发送注册成功的回应
  342. SendMessage("Y", cli);
  343. cout << "注册成功" << endl << "新用户名为:" << username << endl << endl;
  344. continue;
  345. }
  346. else if (infortype[0] == 'G') //群聊消息
  347. {
  348. string message = infortype.substr(1);
  349. string sendername = Getusername(address, userport); //获取发送者姓名
  350. if (sendername == "") continue;
  351. printmessage = "(群消息)" + sendername + ":" + message; //设置要打印的消息
  352. sendmessage = printmessage;
  353. //sendmessage = "G#"+sendername + ":" + message; //设置要转发的消息
  354. }
  355. else if (infortype[0] == 'P') //私聊消息
  356. {
  357. if (infortype[1] == 'L') //获取在线好友列表的请求
  358. {
  359. Sendonlinelist();
  360. continue;
  361. }
  362. if (infortype[1] == 'M') //私聊消息
  363. {
  364. string message = infortype.substr(2);
  365. string sendername = Getusername(address, userport); //提取发送者姓名
  366. if (sendername == "") continue;
  367. //提取接收者姓名
  368. string receivername;
  369. extactPersonalMessageReceivername(message, receivername);
  370. //检查接收者是否离线
  371. int i = Getuserindex(receivername);
  372. if (i == usertable.size()) //接收者已经离线
  373. {
  374. SendMessage("N", cli);
  375. continue;
  376. }
  377. SendMessage("Y", cli); //向发送方发送成功的响应
  378. printmessage = "(私消息)" + sendername + "->" + receivername + ":" + message; //设置要打印的消息
  379. cout << printmessage << endl;
  380. cout << "用户ip:" << address << endl;
  381. cout << "用户端口:" << userport << endl;
  382. cout << "当前在线人数:" << usertable.size() << endl << endl;
  383. sendmessage = printmessage; //设置要发送的消息
  384. SendMessage(sendmessage, usertable[i].receiver);
  385. if (sendername != receivername)
  386. {
  387. int j = Getuserindex(sendername);
  388. SendMessage(sendmessage, usertable[j].receiver);
  389. }
  390. continue;
  391. }
  392. }
  393. else if (infortype == "exit")
  394. {
  395. string sendername = Getusername(address, userport);
  396. if (sendername == "") continue;
  397. int i = Getuserindex(sendername);
  398. if (i >= usertable.size() || i < 0) continue;
  399. SendMessage("exit", usertable[i].receiver); //向该用户显示器发送退出命令
  400. usertable.erase(usertable.begin() + i);
  401. printmessage = "(下线消息)" + sendername + "已下线"; //设置要打印的消息
  402. sendmessage = printmessage; //设置要转发的消息
  403. }
  404. //在服务器上打印消息
  405. cout << printmessage << endl;
  406. cout << "用户ip:" << address << endl;
  407. cout << "用户端口:" << userport << endl;
  408. cout << "当前在线人数:" << usertable.size() << endl << endl;
  409. //向客户端发送消息
  410. for (int i = 0; i < usertable.size(); i++)
  411. SendMessage(sendmessage, usertable[i].receiver);
  412. }
  413. }
  414. int main()
  415. {
  416. server x;
  417. if (x.Startup() == false)
  418. return 0;
  419. if (x.SetServerSocket() == false)
  420. return 0;
  421. x.work();
  422. return 0;
  423. }

客户端发送器的完整代码

  1. #include<Winsock2.h>
  2. #include<iostream>
  3. #include<string>
  4. #include<ctime>
  5. #include<tchar.h>
  6. #include<Windows.h>
  7. #include<fstream>
  8. #include<vector>
  9. #include <sstream>
  10. using namespace std;
  11. #pragma comment(lib,"ws2_32.lib")
  12. #define DEFAULT_PORT 5055
  13. #define DATA_BUFFER 1024
  14. class client
  15. {
  16. public:
  17. bool Startup();
  18. void SetServerAddress();
  19. int GeneratePort(); //随机生成显示器端口号
  20. bool Getonlinelist(); //获得在线的用户名
  21. void work(); //发送器的主函数
  22. private:
  23. WSADATA wsaData;
  24. SOCKET sClient; //发送信息和接收信息时使用的套接字
  25. struct sockaddr_in ser; //保存服务器的地址
  26. int ser_length = sizeof(ser);
  27. struct sockaddr_in communication;
  28. int communication_length = sizeof(communication);
  29. char recv_buf[DATA_BUFFER]; //接收信息的缓冲区
  30. int receiver_port; //显示器的端口号
  31. vector<string> onlinelist; //保存在线用户的用户名
  32. int iSend, iRecv;
  33. };
  34. bool client::Startup()
  35. {
  36. if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
  37. {
  38. cout << "Failed to load Winsock." << endl;
  39. return false;
  40. }
  41. sClient = socket(AF_INET, SOCK_DGRAM, 0);
  42. if (sClient == INVALID_SOCKET)
  43. {
  44. cout << "socket()Failed:" << WSAGetLastError() << endl;
  45. return false;
  46. }
  47. return true;
  48. }
  49. void client::SetServerAddress()
  50. {
  51. cout << "请输入ip地址:";
  52. string iptemp;
  53. cin >> iptemp;
  54. char *ip = new char[iptemp.length() + 1];
  55. strcpy(ip, iptemp.c_str());
  56. //建立服务器端地址
  57. ser.sin_family = AF_INET;
  58. ser.sin_port = htons(DEFAULT_PORT);
  59. ser.sin_addr.s_addr = inet_addr(ip);
  60. }
  61. int client::GeneratePort()
  62. {
  63. srand((unsigned)time(NULL));
  64. int x = 1024 + rand() % (5000 - 1024);
  65. return x;
  66. }
  67. bool client::Getonlinelist() //向服务器请求获取好友在线列表
  68. {
  69. if (onlinelist.size() > 0)
  70. onlinelist.clear();
  71. char getonlinelist[3] = "PL";
  72. iSend = sendto(sClient, getonlinelist, 3, 0, (struct sockaddr*)&ser, ser_length);
  73. if (iSend == SOCKET_ERROR)
  74. {
  75. cout << "sendto()Failed:" << WSAGetLastError() << endl;
  76. return false;
  77. }
  78. memset(recv_buf, 0, sizeof(recv_buf));
  79. iRecv = recvfrom(sClient, recv_buf, sizeof(recv_buf), 0, (struct sockaddr*)&communication, &communication_length); ///
  80. if (iRecv == SOCKET_ERROR)
  81. {
  82. cout << "recvfrom() Failed" << WSAGetLastError() << endl;
  83. return false;
  84. }
  85. string list(recv_buf);
  86. string friendname;
  87. for (int i = 0; i < list.length(); i++)
  88. {
  89. if (list[i] == '$') break;
  90. else if (list[i] == '#')
  91. {
  92. onlinelist.push_back(friendname);
  93. friendname = "";
  94. }
  95. else
  96. friendname = friendname + list[i];
  97. }
  98. cout << "----------------------------" << endl;
  99. cout << "在线好友列表" << endl;
  100. for (int i = 0; i < onlinelist.size(); i++)
  101. cout << i << ": " << onlinelist[i] << endl;
  102. cout << "----------------------------" << endl;
  103. return true;
  104. }
  105. void client::work()
  106. {
  107. while (true)
  108. {
  109. memset(recv_buf, 0, sizeof(recv_buf));
  110. system("cls");
  111. cout << "****************************************" << endl;
  112. cout << "* *" << endl;
  113. cout << "* 1.登录 2.注册 3.退出 *" << endl;
  114. cout << "* *" << endl;
  115. cout << "****************************************" << endl;
  116. string choice;
  117. getline(cin, choice);
  118. if (choice == "1")
  119. {
  120. system("cls");
  121. cout << "请输入用户名:";
  122. string username;
  123. getline(cin, username);
  124. cout << "请输入密码:";
  125. string password;
  126. getline(cin, password);
  127. //产生显示器端口
  128. receiver_port = GeneratePort();
  129. //将端口号写入文件供显示器程序读取
  130. ofstream out("port.txt");
  131. out << receiver_port << "\n" << username;
  132. out.close();
  133. string init_infortemp = "L" + username + "#" + password + "#" + to_string(receiver_port);
  134. char *init_infor = new char[init_infortemp.length() + 1];
  135. strcpy(init_infor, init_infortemp.c_str());
  136. //向服务器验证用户信息
  137. iSend = sendto(sClient, init_infor, init_infortemp.length() + 1, 0, (struct sockaddr*)&ser, ser_length);
  138. //接收服务器回应的消息
  139. iRecv = recvfrom(sClient, recv_buf, sizeof(recv_buf), 0, (SOCKADDR*)&communication, &communication_length);
  140. if (iRecv == SOCKET_ERROR)
  141. {
  142. cout << "recvfrom() Failed:" << GetLastError() << endl;
  143. cout << "未收到服务器的响应,登录失败,请输入Y返回首页:";
  144. string ret;
  145. while (getline(cin, ret))
  146. {
  147. if (ret == "Y")break;
  148. cout << "未收到服务器的响应,登录失败,请输入Y返回首页:";
  149. }
  150. continue;
  151. }
  152. if (recv_buf[0] == 'Y') //登录成功
  153. {
  154. system("cls");
  155. ShellExecute(NULL, _T("open"), _T("receiver.exe"), NULL, NULL, SW_SHOW); //运行显示器程序
  156. }
  157. else if (recv_buf[0] == '0')
  158. {
  159. cout << "未注册用户名,登录失败,请输入Y返回首页:";
  160. string ret;
  161. while (getline(cin, ret))
  162. {
  163. if (ret == "Y")break;
  164. cout << "未注册用户名,登录失败,请输入Y返回首页:";
  165. }
  166. continue;
  167. }
  168. else if (recv_buf[0] == '1')
  169. {
  170. cout << "密码错误,登录失败,请输入Y返回首页:" << endl;
  171. string ret;
  172. while (getline(cin, ret))
  173. {
  174. if (ret == "Y")break;
  175. cout << "密码错误,登录失败,请输入Y返回首页:";
  176. }
  177. continue;
  178. }
  179. else if (recv_buf[0] == '2')
  180. {
  181. cout << "重复登录,登录失败,请输入Y返回首页:" << endl;
  182. string ret;
  183. while (getline(cin, ret))
  184. {
  185. if (ret == "Y")break;
  186. cout << "重复登录,登录失败,请输入Y返回首页:";
  187. }
  188. continue;
  189. }
  190. //选择聊天方式
  191. while (true)
  192. {
  193. system("cls");
  194. cout << "---------------------------------------------------" << endl;
  195. cout << " 用户名:" << username << endl << endl;;
  196. cout << " 1.私聊 2.群聊 3.退出登录 " << endl << endl;
  197. cout << "---------------------------------------------------" << endl;
  198. string mode;
  199. getline(cin, mode);
  200. if (mode == "1") //私聊
  201. {
  202. system("cls");
  203. cout << "私聊模式中,输入return返回上一级" << endl << endl;
  204. if (!Getonlinelist()) continue; //获取好友在线列表失败
  205. cout << "请选择私聊对象的序号" << endl;
  206. string choose;
  207. getline(cin, choose);
  208. if (choose == "return") continue;
  209. int i = 0;
  210. for (i = 0; i < choose.size(); i++)
  211. if (choose[i] > '9' || choose[i] < '0')break;
  212. if (i < choose.size()) continue;
  213. stringstream stream(choose);
  214. int index = 0;
  215. stream >> index;
  216. if (index<0 || index>=onlinelist.size()) continue;
  217. while (true) //向该用户循环发送消息,直到输入return退出
  218. {
  219. system("cls");
  220. cout << "正在和" << onlinelist[index] << "私聊中" << ",输入return返回上一级" << endl << endl;
  221. string message;
  222. getline(cin, message);
  223. if (message == "return")
  224. {
  225. system("cls");
  226. break;
  227. }
  228. message = "PM" + onlinelist[index] + "#" + message;
  229. char *buf = new char[message.length() + 1];
  230. strcpy(buf, message.c_str());
  231. iSend = sendto(sClient, buf, message.length() + 1, 0, (struct sockaddr*)&ser, ser_length);
  232. if (iSend == SOCKET_ERROR)
  233. {
  234. cout << "sendto()Failed:" << WSAGetLastError() << endl;
  235. break;
  236. }
  237. delete[]buf;
  238. iRecv = recvfrom(sClient, recv_buf, sizeof(recv_buf), 0, (SOCKADDR*)&communication, &communication_length);
  239. if (recv_buf[0] == 'Y') continue;
  240. else
  241. {
  242. cout << onlinelist[index] << "已下线" << "输入Y返回主菜单";
  243. string ret;
  244. while (getline(cin, ret))
  245. {
  246. if (ret == "Y") break;
  247. cout << onlinelist[index] << "已下线" << "输入Y返回主菜单";
  248. }
  249. break;
  250. }
  251. }
  252. }
  253. else if (mode == "2") //群聊
  254. {
  255. system("cls");
  256. while (true)
  257. {
  258. system("cls");
  259. cout << "群聊模式,输入return返回上一级" << endl << endl;
  260. string message;
  261. getline(cin, message);
  262. if (message == "return")
  263. {
  264. system("cls");
  265. break;
  266. }
  267. message = "G" + message;
  268. char *buf = new char[message.length() + 1];
  269. strcpy(buf, message.c_str());
  270. iSend = sendto(sClient, buf, message.length() + 1, 0, (struct sockaddr*)&ser, ser_length);
  271. delete[]buf;
  272. if (iSend == SOCKET_ERROR)
  273. {
  274. cout << "sendto()Failed:" << WSAGetLastError() << endl;
  275. break;
  276. }
  277. }
  278. continue;
  279. }
  280. else if (mode == "3") //退出登录
  281. {
  282. char buf[] = "exit";
  283. iSend = sendto(sClient, buf, sizeof(buf), 0, (struct sockaddr*)&ser, ser_length);
  284. break;
  285. }
  286. else
  287. continue;
  288. }
  289. }
  290. else if (choice == "2")
  291. {
  292. system("cls");
  293. cout << "请设置用户名:";
  294. string username;
  295. getline(cin, username);
  296. cout << "请设置登录密码:";
  297. string password;
  298. getline(cin, password);
  299. string init_infortemp = "R" + username + "#" + password;
  300. char *init_infor = new char[init_infortemp.length() + 1];
  301. strcpy(init_infor, init_infortemp.c_str());
  302. //向服务器发送注册用户信息
  303. iSend = sendto(sClient, init_infor, init_infortemp.length() + 1, 0, (struct sockaddr*)&ser, ser_length);
  304. //接收服务器回应的消息
  305. iRecv = recvfrom(sClient, recv_buf, sizeof(recv_buf), 0, (struct sockaddr*)&communication, &communication_length);
  306. if (recv_buf[0] == 'Y')
  307. {
  308. cout << "注册成功" << endl;
  309. continue;
  310. }
  311. else
  312. {
  313. cout << "用户名已存在,注册失败,请输入Y返回首页:" << endl;
  314. string ret;
  315. while (getline(cin, ret))
  316. {
  317. if (ret == "Y")break;
  318. cout << "用户名已存在,注册失败,请输入Y返回首页:";
  319. }
  320. continue;
  321. }
  322. }
  323. else if (choice == "3")
  324. {
  325. closesocket(sClient);
  326. WSACleanup;
  327. return;
  328. }
  329. else
  330. continue;
  331. }
  332. }
  333. int main()
  334. {
  335. client x;
  336. if (x.Startup() == false)
  337. return 0;
  338. x.SetServerAddress();
  339. x.work();
  340. }

客户端接收器的完整代码

  1. #include<WinSock2.h>
  2. #include<iostream>
  3. #include<fstream>
  4. #include<string>
  5. #include<ctime>
  6. #pragma comment(lib,"ws2_32.lib")
  7. using namespace std;
  8. #define DEFAULT_SPORT 5055
  9. #define DEFAULT_CPORT 5056
  10. #define BUFFER_LENGTH 1024
  11. void main()
  12. {
  13. WSADATA wsaData;
  14. if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
  15. {
  16. cout << "Failed to load Winsock." << endl;
  17. return;
  18. }
  19. //建立显示器端地址
  20. struct sockaddr_in receiver;
  21. //读取分配好的端口
  22. ifstream in("port.txt");
  23. string receiver_port;
  24. string username;
  25. getline(in, receiver_port);
  26. getline(in, username);
  27. in.close();
  28. remove("port.txt");
  29. int receiver_port_int = atoi(receiver_port.c_str());
  30. receiver.sin_family = AF_INET;
  31. receiver.sin_port = htons(receiver_port_int); //htons()函数把一个双字节主机字节顺序的数转换为网络字节顺序的数
  32. receiver.sin_addr.s_addr = htonl(INADDR_ANY); //htonl()函数把一个主机字节顺序的数转换为网络字节顺序的数
  33. SOCKET rSocket = socket(AF_INET, SOCK_DGRAM, 0);
  34. if (rSocket == INVALID_SOCKET)
  35. {
  36. cout << "socket()Failed:" << WSAGetLastError() << endl;
  37. return;
  38. }
  39. if (bind(rSocket, (LPSOCKADDR)&receiver, sizeof(receiver)) == SOCKET_ERROR)
  40. {
  41. cout << "bind()Failed:" << WSAGetLastError() << endl;
  42. return;
  43. }
  44. char recv_buf[BUFFER_LENGTH]; //接收数据的缓冲区
  45. memset(recv_buf, 0, sizeof(recv_buf)); //初始化接收缓冲区
  46. struct sockaddr_in ser; //客户端地址
  47. int ser_length = sizeof(ser); //客户端地址长度
  48. cout << "----------------------------------------" << endl << endl;
  49. cout << " 显示器---" << username << endl << endl << endl;
  50. cout << "----------------------------------------" << endl << endl;
  51. while (true) //进入一个无限循环,进行数据接收和发送
  52. {
  53. int iRecv = recvfrom(rSocket, recv_buf, BUFFER_LENGTH, 0, (SOCKADDR*)&ser, &ser_length);
  54. string transmessage(recv_buf);
  55. if (iRecv == SOCKET_ERROR)
  56. {
  57. cout << "recvfrom()Failed:" << WSAGetLastError() << endl;
  58. break;
  59. }
  60. else if (transmessage == "exit") break;
  61. else
  62. cout << transmessage << endl;
  63. }
  64. closesocket(rSocket);
  65. WSACleanup();
  66. }


 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/147100
推荐阅读
  

闽ICP备14008679号