winsock程式之–字串的發送與接收

來源:互聯網
上載者:User

1、伺服器端程式

功能:接收用戶端發來的字串,並把字串原封不動地發送給用戶端

#include <stdio.h>#include <WinSock2.h>#include "mystr.h"#include "mysock.h"#pragma comment(lib, "ws2_32")int main() {    int iResult;    WORD wVersionRequested;    WSADATA wsaData;    SOCKET listenSocket;    SOCKET acceptSocket;    struct sockaddr_in service;    char received[256];    /*    initialize winsock...    create sock...    bind...    listen...    accept...    */    /* read data and send it */    memset(received, 0, sizeof(received));    readString(acceptSocket, received, sizeof(received));    while (strLen(received) > 0 && strCmp(received, "quit") != 0) {        printf("received: %s\n", received);        writeString(acceptSocket, received);        memset(received, 0, sizeof(received));        readString(acceptSocket, received, sizeof(received));    }    printf("bye-bye!\n");    closesocket(listenSocket);    WSACleanup();    return 0;}

2、用戶端程式

功能:將輸入的字串發送給伺服器端,並接收和列印伺服器端發來字串

#include <stdio.h>#include <WinSock2.h>#include "mystr.h"#include "mysock.h"#pragma comment(lib, "ws2_32")int main() {    int iResult;    WORD wVersionRequested;    WSADATA wsaData;    SOCKET clientSocket;    struct sockaddr_in clientService;    char sent[256];    char received[256];    /*    initialize winsock...    create sock...    connect...    */    /* write data and receive it */    memset(sent, 0, sizeof(sent));    printf("> ");    gets_s(sent, sizeof(sent) - 1);    while (strCmp(sent, "quit") != 0) {        writeString(clientSocket, sent);        memset(received, 0, sizeof(received));        readString(clientSocket, received, sizeof(received));        printf("received: %s\n", received);        printf("> ");        gets_s(sent, sizeof(sent) - 1);    }    printf("bye-bye");    closesocket(clientSocket);    WSACleanup();    return 0;}

運行結果如下:

圖1:用戶端程式

圖2:伺服器端程式

註:

程式碼中引用的檔案"mysock.h"請見有關socket資料轉送的函數

程式碼中引用的檔案"mystr.h"請見字串處理函數的實現

程式碼中省略的代碼請見初步認識windows socket伺服器端與用戶端編程

測試環境: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.