SOCKET Server实例

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

#include "stdafx.h"
#include <iostream>
#include "process.h"
#include <Windows.h>
#include <WinSock2.h>
using namespace std;
#pragma comment(lib,"ws2_32.lib")

 

//接受数据
void receive(PVOID param)
{
    SOCKET sock = *((SOCKET*)param);
    char buf[2048] = { 0 };

    int bytes;
    while (1)
    {
        if (SOCKET_ERROR == (bytes = recv(sock, buf, sizeof(buf), 0)))        //rev
        {
            _endthread();
            return;
        }

    }
}

//接受的线程
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);

        if (INVALID_SOCKET == (clientSocket = accept(socketServer, (sockaddr*)&clientAddress, &addrLen)))
        {
            cout << "Receive The Client Failure!" << endl;
            return ;
        }
        _beginthread(receive, 0, &clientSocket);
    }
}

//开始服务
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;
    }

    //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);

    //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;
}

//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;
}

 

你可能感兴趣的:(SOCKET Server实例)