C/C++教程

网络编程--TCP套接字(C/CC++)

本文主要是介绍网络编程--TCP套接字(C/CC++),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

效果图 可实现自由通讯

 

客户端:

#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include <WinSock2.h>
#include <iostream>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")

int main(void)
{
    while (1)
    {
        char sendBuf[50];// = "hello word!";
        scanf("%s", sendBuf);
        WORD wVersion;
        WSADATA wsaData;
        int err;

        wVersion = MAKEWORD(1, 1);
        err = WSAStartup(wVersion, &wsaData);

        if (err != 0) return err;

        if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)
        {
            WSACleanup();
            return-1;
        }

        //创建套接字
        SOCKET sockCli = socket(AF_INET, SOCK_STREAM, 0);

        SOCKADDR_IN addrs;
        addrs.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
        addrs.sin_family = AF_INET;
        addrs.sin_port = htons(5000);

        //向服务器发起连接请求
        connect(sockCli, (SOCKADDR*)&addrs, sizeof(SOCKADDR));

        //接收数据
        char recvBuf[100];
        recv(sockCli, recvBuf, 100, 0);
        std::cout << recvBuf << std::endl;

        //发送数据
        send(sockCli, sendBuf, 100, 0);

        closesocket(sockCli);
        WSACleanup();

        std::cin.get();
}
    
    return 0;
}

服务端:

#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <WinSock2.h>
#include <iostream>
#pragma comment(lib,"ws2_32.lib")

int main(void)
{
    //加载套接字库
    WORD wVersionRequested;//版本要求
    WSADATA wsaData;
    int err;

    wVersionRequested = MAKEWORD(1, 1);//版本
    //初始化套接字库
    err = WSAStartup(wVersionRequested, &wsaData);

    if (err != 0)  return err;

    if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1) return -1;//低字节 高字节

    //新建套接字

    SOCKET sockS = socket(AF_INET, SOCK_STREAM, 0);//AF_INET IPV4    SOCK_STREAM == TCP
    SOCKADDR_IN addrs;
    addrs.sin_addr.S_un.S_addr = htonl(INADDR_ANY); //htonl    字节顺序
    addrs.sin_family = AF_INET;//IPV4
    addrs.sin_port = htons(5000);//端口号

    //绑定套接字到本地IP,
    bind(sockS, (SOCKADDR*)&addrs, sizeof(SOCKADDR));

    //开始监听
    listen(sockS, 5);

    SOCKADDR_IN addrCil;
    int len = sizeof(SOCKADDR);

    while (true)
    {
        //接收客户连接
        SOCKET sockConn = accept(sockS, (SOCKADDR*)&addrCil, &len);
        char sendBuf[100];
        sprintf_s(sendBuf, 100, "Welcome %s to qiniu!", inet_ntoa(addrCil.sin_addr));

        //发送数据
        send(sockConn, sendBuf, strlen(sendBuf) + 1, 0);

        char recvBuf[100];
        //接收数据
        recv(sockConn, recvBuf, 100, 0);

        std::cout << recvBuf << std::endl;
        closesocket(sockConn);
    }
    closesocket(sockS);
    WSACleanup();

    return 0;
}

 

这篇关于网络编程--TCP套接字(C/CC++)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!