win7下。C++实现多人聊天室上
来源:互联网 发布:软件架构师薪水 编辑:程序博客网 时间:2024/05/22 08:04
.这个是服务端。
#define _WINSOCK_DEPRECATED_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS#ifndef _H_H_#define _H_H_#include <thread>#include <iostream>#include <string>#include <WinSock2.h>#include <stdlib.h>#pragma comment(lib,"ws2_32.lib")using namespace std;static struct MyStruct{SOCKET sock;int empt;}soc[4];class Server{ public:Server();~Server();static void talk(int id);private:SOCKET s;};#endif // _H_H_
#include "h.h"Server::Server(){WSADATA wsadata;WORD v = MAKEWORD(2, 2);if (::WSAStartup(v, &wsadata) < 0)exit(0);s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);sockaddr_in sin;sin.sin_family = AF_INET;sin.sin_port = htons(4567);sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");if (::bind(s, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR)return;if (::listen(s, 5) == SOCKET_ERROR)return;cout << "The server has been started " << endl;while (1){int i;for ( i = 0; i < 4; i++){if (soc[i].empt==0){soc[i].empt = 1;break;}}sockaddr_in re;int n = sizeof(re);soc[i].sock = ::accept(s, (SOCKADDR*)&re, &n);if (soc[i].sock==INVALID_SOCKET){return;}std::thread t(talk, i);t.detach();}closesocket(s);}Server::~Server(){::WSACleanup();}void Server::talk(int id){char hello[] = "Welcome";::send(soc[id].sock, hello, 7, 0);while (true){char buff[255];int nR = ::recv(soc[id].sock, buff, 256, 0);if (nR>0){buff[nR] = '\0';char buf[300]; _itoa(id, buf, 10); strcat(buf, buff);for (int i = 0; i < 4; i++){if (soc[i].empt){::send(soc[i].sock, buf, strlen(buf), 0);}}}else{closesocket(soc[id].sock);soc[id].empt = 0;return;}}}
#include "h.h"int main(){Server server;return 0;}想法是接收数据。收到以后。把信息发给所有连接在线的人。
0 0
- win7下。C++实现多人聊天室上
- Linux下C实现的聊天室
- Linux下C实现的聊天室
- Linux下C实现的聊天室
- Socket编程实现多人聊天室(c语言版)
- linux下使用UDP实现简易的多人聊天室
- Linux下实现聊天室
- 利用多线程实现linux下C语言的聊天室程序:
- 【linux】多人聊天室实现
- java实现多人聊天室
- Android实现C/S聊天室
- linux下 UDP 实现聊天室
- linux系统下实现聊天室
- Linux C 多人网络聊天室(UDP)
- linux下 socket的多人聊天室
- MiNa 实现多人聊天室程序
- Apache MiNa 实现多人聊天室
- Apache MiNa 实现多人聊天室
- Java日志管理:Logger.getLogger()和LogFactory.getLog()的区别(详解Log4j)
- 统计相关系数(1)——Pearson(皮尔逊)相关系数及MATLAB实现
- Matplotlib 入门教程
- 【springboot】使用注解遇到的问题
- CocoaPods使用详解
- win7下。C++实现多人聊天室上
- log4j配置参数详解
- Cookie/Session机制详解
- 数据结构::搜索二叉树
- SASS用法指南
- python写些小工具urluncode编码urlencode解码、MD5加密、二进制转义、时间戳转换
- 理解AsynchronousChannelGroup
- redis导库
- Java的匹配正则表达式Pattern和Matcher