网络编程

Posted sunshine-gzw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了网络编程相关的知识,希望对你有一定的参考价值。

#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] = ;
            if (strstr(buf, "quit") != NULL)
            {
                char ce[] = "quit success!
";
                send(client, ce, strlen(ce) + 1, 0);
                break;
            }
            int sendlen = send(client, "ok
", 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失败!
");
        return -1;
    }
    printf("创建成功,socket=[%d]
", 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("绑定失败!
");
        return -2;
    }
    printf("绑定端口号成功,端口号为:[%d]
", 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
", client);

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

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


    while (1);
    return  0;
}

效果:

技术图片

 

 技术图片

 

 技术图片

 

以上是关于网络编程的主要内容,如果未能解决你的问题,请参考以下文章

VSCode自定义代码片段14——Vue的axios网络请求封装

VSCode自定义代码片段14——Vue的axios网络请求封装

VSCode自定义代码片段14——Vue的axios网络请求封装

使用 Pygments 检测代码片段的编程语言

面向面试编程代码片段之GC

如何在 Django Summernote 中显示编程片段的代码块?