C/C++使用socket实现server和client

Server代码

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


int     main(int argc,char *argv[])
{

    WSADATA wsaData;
    WSAStartup(MAKEWORD(2,2),&wsaData);//初始化

    SOCKET  s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);

    sockaddr_in sockaddr;
    sockaddr.sin_family = PF_INET;
    sockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
    sockaddr.sin_port = htons(234);

    bind(s,(const struct sockaddr *)&sockaddr,sizeof(sockaddr));
    //在本地绑定234端口
    listen(s,1);//开始监听

    //wait for connection
    SOCKET  client;
    int nsize = sizeof(SOCKADDR);
    SOCKADDR    clientAddr;
    printf("wait for connection...\n");
    client = accept(s,&clientAddr,&nsize);//等待客户端连接
    //start send message
    printf("start to send msg...\n");
    send(client,"hello",5,NULL);
    closesocket(client);
    closesocket(s);

    WSACleanup();
    return 0;
}

Client代码

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


int     main(int argc,char *argv[])
{

    WSADATA wsaData;
    WSAStartup(MAKEWORD(2,2),&wsaData);//初始化

    SOCKET  s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);

    sockaddr_in sockaddr;
    sockaddr.sin_family = PF_INET;
    sockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
    sockaddr.sin_port = htons(234);//设置要连接的IP和端口

    connect(s,(SOCKADDR*)&sockaddr,sizeof(SOCKADDR));//tcp连接
    char    buffer[200] = {0};
    recv(s,buffer,200,NULL);//

    printf("response:%s\n",buffer);
    WSACleanup();
    return 0;
}

C/C++使用socket实现server和client_第1张图片

你可能感兴趣的:(c++,C#)