// PigServer.cpp : 定義控制檯應用程序的入口點。
//ios
#include "stdafx.h"
#include <iostream>
#include "process.h"
#include <Windows.h>
#include <WinSock2.h>
using namespace std;
#pragma comment(lib,"ws2_32.lib")socket
//接受數據
void receive(PVOID param)
{
SOCKET sock = *((SOCKET*)param);
char buf[2048] = { 0 };spa
int bytes;
while (1)
{
if (SOCKET_ERROR == (bytes = recv(sock, buf, sizeof(buf), 0))) //rev
{
_endthread();
return;
}線程
}
}server
//接受的線程
void ReceiveConnectThread(void *param)
{
SOCKET socketServer = *((SOCKET*)param);
while (1)//不斷接受來自Client的數據
{
SOCKET clientSocket; //Receive the client
sockaddr_in clientAddress;
memset(&clientAddress, 0, sizeof(clientAddress));
int addrLen = sizeof(clientAddress);it
if (INVALID_SOCKET == (clientSocket = accept(socketServer, (sockaddr*)&clientAddress, &addrLen)))
{
cout << "Receive The Client Failure!" << endl;
return ;
}
_beginthread(receive, 0, &clientSocket);
}
}io
//開始服務
SOCKET StartServer()
{
SOCKET serverSocket;//Inintiate
//Create Failure
if (INVALID_SOCKET == (serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)))
{
cout << "Create Socket Error!" << endl;
return 0;
}thread
//Create Success
sockaddr_in serverAddress;
memset(&serverAddress,0,sizeof(sockaddr_in));
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
serverAddress.sin_port = htons(9224);stream
//bind
if (SOCKET_ERROR == (bind(serverSocket, (sockaddr*)&serverAddress, sizeof(serverAddress))))
{
cout << "socket bind error" << endl;
return 0;
}
//listen
if (SOCKET_ERROR == (listen(serverSocket, SOMAXCONN)))
{
cout << "Listern Erroe!" << endl;
return 0;
}
return serverSocket;
}cli
//main
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsa;
if (0 != WSAStartup(MAKEWORD(2, 2), &wsa))
{
cout << "Init Sockt Error!" << endl;
return -1;
}
SOCKET sockt=StartServer();
_beginthread(ReceiveConnectThread, 0, &sockt);
system("pause");
return 0; }