winsock程序之--字符串的发送与接收

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值