socket

#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
void main()
{

// 初始化
    WSADATA wsaData;
    int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
    if ( iResult != NO_ERROR )
        printf("Error at WSAStartup()\n");

// 建立socket
    SOCKET server;
    server = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );

    if ( server == INVALID_SOCKET )
    {
        printf( "Error at socket(): %ld\n", WSAGetLastError() );
        WSACleanup();
        return;
    }

// 绑定socket
    sockaddr_in service;
    service.sin_family = AF_INET;
    service.sin_addr.s_addr = inet_addr( "127.0.0.1" );
    service.sin_port = htons(27015 );

    if ( bind( server, (SOCKADDR*) &service, sizeof(service) ) == SOCKET_ERROR )
    {
        printf( "bind() failed.\n" );
        closesocket(server);
        return;
    }

// 监听 socket
    if ( listen( server, 1 ) == SOCKET_ERROR )
        printf( "Error listening on socket.\n");

// 接受连接
    SOCKET AcceptSocket;
    char *buffer="欢迎光临\n";
    printf( "Waiting for a client to connect...\n" );
    while (1)
    {
        AcceptSocket = SOCKET_ERROR;
        while ( AcceptSocket == SOCKET_ERROR )
        {
            AcceptSocket = accept( server, NULL, NULL );
            send(AcceptSocket,buffer,sizeof(buffer),0);
        }
        printf( "Client Connected.\n");
       // server = AcceptSocket;
    }

// 发送接受数据
    int bytesSent;
    int bytesRecv = SOCKET_ERROR;
    char sendbuf[32] = "Server: Sending Data.";
    char recvbuf[32] = "";

    bytesRecv = recv( server, recvbuf, 32, 0 );
    printf( "Bytes Recv: %ld\n", bytesRecv );

    bytesSent = send( server, sendbuf, strlen(sendbuf), 0 );
    printf( "Bytes Sent: %ld\n", bytesSent );
    closesocket(server);
    return;
}

你可能感兴趣的:(socket)