码迷,mamicode.com
首页 > 其他好文 > 详细

VC小工具.最简单TCP服务器

时间:2018-10-20 00:14:17      阅读:312      评论:0      收藏:0      [点我收藏+]

标签:details   \n   vc6   failed   pre   list   wsad   blog   col   

1、C++基于TCP_IP简单的客户端、服务器通信程序实例 - happy_xiahuixiax的博客 - CSDN博客.html(https://blog.csdn.net/happy_xiahuixiax/article/details/72627426

2、

3、代码:(VC6 编译通过,未测试...)

#include <WinSock2.h>  
#include <stdio.h>  
#include <stdlib.h>  

#pragma comment(lib, "ws2_32.lib")  

void main()  
{  
    WSADATA wsaData;  
    int port = 8000;  

    char buf[] = "Server: hello, I am a server.....";   

    if(WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)  
    {  
        printf("Failed to load Winsock");  
        return;  
    }  

    //创建用于监听的套接字  
    SOCKET sockSrv = socket(AF_INET, SOCK_STREAM, 0);  

    SOCKADDR_IN addrSrv;  
    addrSrv.sin_family = AF_INET;  
    addrSrv.sin_port = htons(port); //1024以上的端口号  
    addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);  

    int retVal = bind(sockSrv, (LPSOCKADDR)&addrSrv, sizeof(SOCKADDR_IN));  
    if(retVal == SOCKET_ERROR){  
        printf("Failed bind:%d\n", WSAGetLastError());  
        return;  
    }  

    if(listen(sockSrv,10) ==SOCKET_ERROR){  
        printf("Listen failed:%d", WSAGetLastError());  
        return;  
    }  

    SOCKADDR_IN addrClient;  
    int len = sizeof(SOCKADDR);  

    while(1)  
    {  
        //等待客户请求到来    
        SOCKET sockConn = accept(sockSrv, (SOCKADDR *) &addrClient, &len);  
        if(sockConn == SOCKET_ERROR){  
            printf("Accept failed:%d", WSAGetLastError());  
            break;  
        }  

        printf("Accept client IP:[%s]\n", inet_ntoa(addrClient.sin_addr));  

        //发送数据  
        int iSend = send(sockConn, buf, sizeof(buf) , 0);  
        if(iSend == SOCKET_ERROR){  
            printf("send failed");  
            break;  
        }  

        char recvBuf[100];  
        memset(recvBuf, 0, sizeof(recvBuf));  
//      //接收数据  
        recv(sockConn, recvBuf, sizeof(recvBuf), 0);  
        printf("%s\n", recvBuf);  

        closesocket(sockConn);  
    }  

    closesocket(sockSrv);  
    WSACleanup();  
    system("pause");  
}

 

4、

5、

 

VC小工具.最简单TCP服务器

标签:details   \n   vc6   failed   pre   list   wsad   blog   col   

原文地址:https://www.cnblogs.com/CodeHouseZ/p/9819906.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!