C++基于socket的多线程的群聊程序(TCP)

参考了:http://www.cnblogs.com/jzincnblogs/p/5189636.html 给了很大的启示

话不多说,直接上码。

服务器端

服务器端头文件(server.h)

#ifndef SERVER_H
#define SERVER_H

#include

#pragma comment(lib,"ws2_32.lib")

class Server
{
public:
	Server();
	~Server();
	void WaitForClient();
private:
	WORD winsock_ver;
	WSADATA wsa_data;
	SOCKET sock_svr;
	SOCKET sock_clt;
	HANDLE h_thread;
	SOCKADDR_IN addr_svr;
	SOCKADDR_IN addr_clt;
	int res_val;
	int addr_len;
	char buf_IP[129];
};

struct Parameter//用来传参 使得CreateThread()可以传递多个参数
{
	SOCKET sock_clt;
	SOCKADDR_IN addr_clt;
};

#endif


服务器端(server.cpp)

#include "server.h"
#include
#include
#include
using namespace std;

#define SER_PORT 8888
#define MaxSize 500

Server::Server()//构造函数
{
	//初始化winsock
	winsock_ver = MAKEWORD(2,2);
	addr_len = sizeof(SOCKADDR_IN);
	addr_svr.sin_family = AF_INET;
	addr_svr.sin_port = htons(SER_PORT);
	addr_svr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
	memset(buf_IP,0,sizeof(buf_IP));
	res_val = WSAStartup(winsock_ver,&wsa_data);
	if(res_val != 0)
	{
		cout<<"WSAStratup error!"<sock_clt;
	SOCKADDR_IN addr_clt = para_clt->addr_clt;
	char buf_msg[MaxSize];
	int res_val = 0;
	while(true)
	{
		memset(buf_msg,0,MaxSize);
		res_val = recv(sock_clt,buf_msg,MaxSize,0);
		if(res_val < 0)
		{
			cout<<"Failed to receive message from client!Error code:"<

在主函数调用Server类的WaitForClient()函数。


客户端

客户端头文件(client.h)

#ifndef CLIENT_H
#define CLIENT_H

#include

class Client
{
public:
	Client();
	~Client();
	void Send();
private:
	WORD winsock_ver;
	WSADATA wsa_data;
	SOCKET sock_clt;
	SOCKADDR_IN addr_clt;
	int res_val;
	int addr_len;
};

#endif


客户端(client.cpp)

#include "client.h"
#include
#include
using namespace std;

#pragma comment(lib,"ws2_32.lib")

#define MaxSize 500
#define SER_PORT 8888

Client::Client()//构造函数
{
	//初始化winsock
	winsock_ver = MAKEWORD(2,2);
	addr_len = sizeof(SOCKADDR_IN);
	addr_clt.sin_family = AF_INET;
	addr_clt.sin_port = htons(SER_PORT);
	addr_clt.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
	res_val = WSAStartup(winsock_ver,&wsa_data);
	if(res_val != 0)
	{
		cout<<"WSAStartup error!"<>buf_msg;
		//发消息
		res_val = send(sock_clt, buf_msg, sizeof(buf_msg), 0);
		if(res_val == SOCKET_ERROR)
		{
			cout<<"Failed to send message to server!Error code:"<

在主函数调用Client类的Send()函数。

过程实际和单线程的通信是一样的,详见:http://blog.csdn.net/x3i__x3i/article/details/79573209。不同在于服务器端需要通过创建线程来接收来自不同客户端的连接。


你可能感兴趣的:(socket)