初步認識windows socket伺服器端與用戶端編程

來源:互聯網
上載者:User

1、伺服器端

通訊模型:初始化winsock -> 建立socket -> 綁定(bind) -> 監聽(listen) -> 接收(accept)

/** * main.c * socket server * @date   : 2011/11/27 * @author : MJN */#include <stdio.h>#include <winsock2.h>#pragma comment(lib, "ws2_32")int main() {    int iResult;    WORD wVersionRequested;    WSADATA wsaData;    SOCKET listenSocket;    SOCKET acceptSocket;    struct sockaddr_in service;        /* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */    wVersionRequested = MAKEWORD(2, 2);    /* Initializing Winsock */    iResult = WSAStartup(wVersionRequested, &wsaData);    if (iResult != 0) {        printf("WSAStartup failed with error: %d\n", iResult);        return -1;    } else {        printf("WSAStartup succeeded!\n");    }    if (wsaData.wVersion != wVersionRequested) {        printf("the socket version loaded is: %d.%d, but is not the requested %d.%d",             HIBYTE(wsaData.wVersion), LOBYTE(wsaData.wVersion),             HIBYTE(wVersionRequested), LOBYTE(wVersionRequested));        WSACleanup();        return -1;    }    /* create a tcp socket */    listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);    if (listenSocket == INVALID_SOCKET) {        printf("create socket falied with error: %d\n", WSAGetLastError());        WSACleanup();        return -1;    } else {        printf("socket created!\n");    }    /* bind the socket */    service.sin_family = AF_INET;    service.sin_port = htons(9999);    service.sin_addr.s_addr = inet_addr("127.0.0.1");    iResult = bind(listenSocket, (SOCKADDR *) &service, sizeof(service));    if (iResult == SOCKET_ERROR) {        printf("bind failed with error:%d\n", WSAGetLastError());        closesocket(listenSocket);        WSACleanup();        return -1;    } else {        printf("bind succeeded!\n");    }    /* listen for incoming connection requests */    iResult = listen(listenSocket, SOMAXCONN);    if (iResult == SOCKET_ERROR) {        printf("listen failed with error:%d\n", WSAGetLastError());        closesocket(listenSocket);        WSACleanup();        return -1;    } else {        printf("listen succeeded!\n");    }    printf("listening on socket...\n");    /* accept new incoming connections */    while (1) {        acceptSocket = accept(listenSocket, NULL, NULL);        if (acceptSocket == INVALID_SOCKET) {            printf("accept failed with error: %d", WSAGetLastError());            closesocket(listenSocket);            WSACleanup();            return -1;        } else {            printf("accepted a new socket with id: %d\n", acceptSocket);        }    }    closesocket(listenSocket);    WSACleanup();    return 0;

2、用戶端

通訊模型:初始化winsock -> 建立socket -> 串連(connect)

/** * main.c * socket client * @date   : 2011/11/27 * @author : MJN */#include <stdio.h>#include <WinSock2.h>#pragma comment(lib, "ws2_32")int main() {    int iResult;    WORD wVersionRequested;    WSADATA wsaData;    SOCKET clientSocket;    struct sockaddr_in clientService;    wVersionRequested = MAKEWORD(2, 2);        /* initialize windows socket */    iResult = WSAStartup(wVersionRequested, &wsaData);    if (iResult != 0) {        printf("WSAStartup failed with error: %d\n", iResult);        return -1;    } else {        printf("WSAStartup succeeded!\n");    }    /* create client tcp socket */    clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);    if (clientSocket == INVALID_SOCKET) {        printf("create socket failed with error: %d\n", WSAGetLastError());        WSACleanup();        return -1;    } else {        printf("create socket succeeded!\n");    }    /* connect to server */    clientService.sin_family = AF_INET;    clientService.sin_port = htons(9999);    clientService.sin_addr.s_addr = inet_addr("127.0.0.1");    iResult = connect(clientSocket, (SOCKADDR *) &clientService, sizeof(clientService));    if (iResult == SOCKET_ERROR) {        printf("connect failed with error: %d\n", WSAGetLastError());        closesocket(clientSocket);        WSACleanup();        return -1;    } else {        printf("connect succeed!\n");    }    closesocket(clientSocket);    WSACleanup();    return 0;}

註:

IDE:Microsoft Visual Studio 2010

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.