Win32多线程套接字(服务端)

服务端

   1、初始化Windows Socket库。
   2、创建Socket。
   3、绑定Socket。
   4、监听。
   5、Accept(创建一个线程)。
   6、接收、发送数据(在线程中)。

需要在连接器的输入选项中加入WS2_32.lib

 

// TcpServer.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <windows.h>
#include <iostream>
using namespace std;

//创建套接字,bind,listen,accept
DWORD WINAPI clientThread(LPVOID lpParameter);

int _tmain(int argc, _TCHAR* argv[])
{
	WSADATA Ws;
	SOCKET serverSocket,clientSocket;
	struct sockaddr_in serverAddr,clientAddr;
	int Ret=0;
	if ( WSAStartup(MAKEWORD(2,2), &Ws) != 0 )
	{
		cout<<"Init Windows Socket Failed::"<<GetLastError()<<endl;
		return -1;
	}
	
	serverSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	
	if ( serverSocket == INVALID_SOCKET )
    {
		cout<<"Create Socket Failed::"<<GetLastError()<<endl;
		return -1;
    }
	 
	serverAddr.sin_family = AF_INET;
	serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);//可能出现多网卡的情况,INADDR_ANY可以简化
	serverAddr.sin_port = htons(8000);
	
	//Bind Socket
	Ret = bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
	if ( Ret != 0 )
	{
		cout<<"Bind Socket Failed::"<<GetLastError()<<endl;
		return -1;
	}

	Ret = listen(serverSocket, 10);//同时并发连接为10个
	if ( Ret != 0 )
	{
		cout<<"listen Socket Failed::"<<GetLastError()<<endl;
		return -1;
	}

	int len=sizeof(clientAddr);
	while(TRUE)
	{
		clientSocket=accept(serverSocket,(SOCKADDR *)&clientAddr,&len);//获得一个客户端
		if ( clientSocket == INVALID_SOCKET )
	        {
				cout<<"Accept Failed::"<<GetLastError()<<endl;
				break;
			}
		cout<<"客户端连接::"<<inet_ntoa(clientAddr.sin_addr)<<":"<<clientAddr.sin_port<<endl;
		HANDLE hThread=CreateThread(NULL, 0, clientThread, (LPVOID)clientSocket, 0, NULL);
		if ( hThread == NULL )
			{
				cout<<"Create Thread Failed!"<<endl;
				break;
			} 
		CloseHandle(hThread);
	}

	closesocket(serverSocket);
	WSACleanup();
	return 0;
}

DWORD WINAPI clientThread(LPVOID lpParameter)
{
	SOCKET CientSocket = (SOCKET)lpParameter;
	int Ret = 0;
	char RecvBuffer[MAX_PATH]; 
	while ( true )
		{
			memset(RecvBuffer, 0x00, sizeof(RecvBuffer));
			int Ret = recv(CientSocket, RecvBuffer, MAX_PATH, 0);
			if ( Ret == 0 || Ret == SOCKET_ERROR ) 
			{
				cout<<"客户端退出!"<<endl;
				closesocket(CientSocket);//关闭客户端套接字
				break;
			}
			cout<<"接收到客户信息为:"<<RecvBuffer<<endl;
		}
	
		return 0;
}

 

你可能感兴趣的:(Win32)