Win32 멀티스레드 소켓 (서버)
3088 단어 Win32
1. Windows Socket 라이브러리를 초기화합니다.2. 소켓을 만든다.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;
}