win7下。C++实现多人聊天室上

.这个是服务端。
#define _WINSOCK_DEPRECATED_NO_WARNINGS 
#define  _CRT_SECURE_NO_WARNINGS
#ifndef _H_H_
#define _H_H_
#include 
#include 
#include 
#include 
#include 
#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;
}
想法是接收数据。收到以后。把信息发给所有连接在线的人。

你可能感兴趣的:(C++,基础,socket)