TCP通讯(服务端)

修改自网络:

#include <stdio.h>
#include <string.h>

#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")

int Server(void);

int main(int argc, char *argv[])
{
    return Server();
}

int Server(void)
{
    WSADATA wsaData;
    SOCKET iSockRawID, iSockNewID;
    struct sockaddr_in stCliAddr, stServAddr;
    int clilen;
    int ret;
    char buff[1024];

    if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
    {
        printf("Error at WSAStartup().\n");
        return 255;
    }

    if ((iSockRawID = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        printf("Server: Can not open a stream socket!\n");
        return 1;
    }

    stServAddr.sin_family = AF_INET;
    stServAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
    stServAddr.sin_port = htons(8001);
    if ((bind(iSockRawID, (struct sockaddr *)&stServAddr, sizeof(struct sockaddr))) < 0)
    {
        printf("Server: Con not bind address!\n");
        return 2;
    }
    listen(iSockRawID, SOMAXCONN);
    while (1)
    {
        clilen = sizeof (struct sockaddr_in);
        iSockNewID = accept(iSockRawID, (struct sockaddr *)&stCliAddr, &clilen);
        if (iSockNewID < 0)
        {
            printf("Server: Accept error!\n");
            return 3;
        }
        else
        {
            memset(buff, 0, sizeof(buff));
            ret = recv(iSockNewID, buff, sizeof (buff)-1, 0);
            printf("Client[%s:%i]: %s\n", inet_ntoa(stCliAddr.sin_addr), ntohs(stCliAddr.sin_port), buff);
            ret = send(iSockNewID, buff, strlen(buff), 0);
            closesocket(iSockNewID);
        }
    }
    closesocket(iSockRawID);
    return 0;
}


你可能感兴趣的:(TCP通讯(服务端))