一个简单的基于WINDOWS平台的套接字通信

一、流程图

二、注意事项

1.连接ws2_32库

 

2.使用inet_addr函数报错解决

 

三、代码

服务端:

#include "stdio.h"
#include "stdlib.h"
#include "winsock2.h"


int main(int argc, char* argv[])
{
    WSADATA wsaData;
    SOCKET hSerSocket,hClntSock;
    SOCKADDR_IN servAddr, clntAddr;

    char message[] = "hello world!";
    int szClntAddr;
    int size;

    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
        printf("WSAStartup() error!\n");

    hSerSocket = socket(PF_INET, SOCK_STREAM, 0);
    if (hSerSocket == INVALID_SOCKET)
        printf("socket() error!\n");

    memset(&servAddr, 0, sizeof(servAddr));
    servAddr.sin_family = AF_INET;
    servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servAddr.sin_port = htons(9190);


    if (bind(hSerSocket, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR)
        printf("bind() error!\n");

    if(listen(hSerSocket, 5) == SOCKET_ERROR)
        printf("listen() error!\n");

    szClntAddr = sizeof(clntAddr);
    hClntSock = accept(hSerSocket, (SOCKADDR*)&clntAddr,&szClntAddr);
    if(hClntSock == INVALID_SOCKET)
        printf("accept() error!\n");

    send(hClntSock,message,sizeof(message),0);

    closesocket(hSerSocket);
    closesocket(hClntSock);
    WSACleanup();
    return 0;
}

客户端:

#include "stdio.h"
#include "stdlib.h"
#include "winsock2.h"


int main(int argc, char* argv[])
{
    WSADATA wsaData;
    SOCKET hSocket;
    SOCKADDR_IN servAddr;

    char message[30];
    int strLen;

    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
        printf("WSAStartup() error!\n");

    hSocket = socket(PF_INET, SOCK_STREAM, 0);
    if (hSocket == INVALID_SOCKET)
        printf("socket() error!\n");

    memset(&servAddr, 0, sizeof(servAddr));
    servAddr.sin_family = AF_INET;
    servAddr.sin_addr.s_addr = inet_addr(argv[1]);
    servAddr.sin_port = htons(atoi(argv[2]));
    if (connect(hSocket, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR)
        printf("connect() error!\n");

    strLen = recv(hSocket, message, sizeof(message) - 1, 0);
    if (strLen == -1)
        printf("recv() error!\n");

    printf("Message:%s\n",message);
    closesocket(hSocket);
    WSACleanup();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值