网络编程(一)

#ifdef WIN32
#include<windows.h>
#else
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/socket.h>
#define closesocket close;
#endif 
#include<stdio.h>
#include<thread>
class Tcp
{
public:
    void Main()
    {
        char buf[1024] = { 0 };
        for (;;)
        {
            int recvlen = recv(client, buf, sizeof(buf) - 1, 0);
            if (recvlen<0)
            {
                break;
            }
            buf[recvlen] = '\0';
            if (strstr(buf, "quit") != NULL)
            {
                char ce[] = "quit success!\n";
                send(client, ce, strlen(ce) + 1, 0);
                break;
            }
            int sendlen = send(client, "ok\n", 4, 0);

            printf("%s", buf);
        }
        closesocket(client);
        delete this;
    }
    int client = 0;
};
int main(int argc, char *argv[])
{
#ifdef WIN32
    WSADATA ws;
    WSAStartup(MAKEWORD(2, 2), &ws);
#endif

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == -1)
    {
        printf("创建socket失败!\n");
        return -1;
    }
    printf("创建成功,socket=[%d]\n", sock);

    unsigned short port = 8080;
    if (argc > 1)
    {
        port = atoi(argv[1]);
    }
    sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
#ifdef WIN32
    server.sin_addr.S_un.S_addr = htonl(0);
#else
    server.sin_addr.s_addr = htonl(0);
#endif
    if (bind(sock, (sockaddr*)&server, sizeof(server)) != 0)
    {
        printf("绑定失败!\n");
        return -2;
    }
    printf("绑定端口号成功,端口号为:[%d]\n", port);

    listen(sock, 10);

    for (;;)
    {
        sockaddr_in  client_sock;
        socklen_t len = sizeof(client_sock);

        int client = accept(sock, (sockaddr*)&client_sock, &len);
        if (client <= 0)break;
        printf("accept sock=%d\n", client);

        char *str = inet_ntoa(client_sock.sin_addr);
        unsigned short client_port = ntohs(client_sock.sin_port);

        printf("ip:%s port=%d\n", str, client_port);
        Tcp* p = new Tcp();
        p->client = client;
        std::thread th(&Tcp::Main,p);
        th.detach();
    }
    closesocket(sock);


    while (1);
    return  0;
}

效果:

 

 

 

 

 

posted @ 2020-07-29 13:36  sunshine_gzw  阅读(105)  评论(0编辑  收藏  举报