chenluhua1980
8 天以前 b25ce186da97a1a774ddf89504f97d8c244fda66
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#pragma once
#ifndef SOCKET_COMM_H
#define SOCKET_COMM_H
 
#include <winsock2.h>
#include <ws2tcpip.h>
#include <string>
#include <vector>
#include <iostream>
 
#pragma comment(lib, "ws2_32.lib")
 
class SocketComm {
public:
    SocketComm();
    ~SocketComm();
 
    bool createClientSocket(const std::string& serverIP, uint16_t serverPort); // ¿Í»§¶Ë
    bool createServerSocket(uint16_t port);                                     // ·þÎñ¶Ë£¨¼àÌý£©
 
    // ÐÂÔö£º·Ç×èÈû accept/ÊÕ·¢/¹Ø±ÕÖ¸¶¨¿Í»§¶Ë
    bool acceptOne(SOCKET& outClient, std::string& outIp, uint16_t& outPort);
    bool recvFrom(SOCKET s, std::vector<uint8_t>& buffer, bool& peerClosed);
 
    // ¿ÉÑ¡£ºÎªÁ˼æÈݾɵ÷Ó㬱£ÁôÒ»¸öÄÚÁª°ü×°£¨Èç¹ûÆäËüµØ·½»¹Óõ½Á˾ÉÇ©Ãû£©
    inline bool recvFrom(SOCKET s, std::vector<uint8_t>& buffer) {
        bool closed = false;
        return recvFrom(s, buffer, closed);
    }
    bool sendTo(SOCKET s, const std::vector<uint8_t>& data);
    void closeClient(SOCKET s);
 
    void closeSocket(); // ¹Ø±Õ¼àÌý»òµ¥Á¬½Ó
 
    // ¹©ÉϲãÅжϱ¾¶ÔÏóµ±Ç°ÊÇ·ñÊÇ¡°¼àÌýģʽ¡±
    bool isListening() const { return listenSock != INVALID_SOCKET; }
    bool sendDataSingle(const std::vector<uint8_t>& data); // ¿Í»§¶Ëµ¥Á¬½Ó·¢ËÍ
    bool recvSingle(std::vector<uint8_t>& buffer);         // ¿Í»§¶Ëµ¥Á¬½Ó½ÓÊÕ
 
private:
    SOCKET listenSock = INVALID_SOCKET; // ¼àÌý socket£¨·þÎñ¶Ë£©
    SOCKET sock = INVALID_SOCKET; // µ¥Á¬½Óģʽ£¨¿Í»§¶ËʱÓã©
    WSADATA wsaData{};
 
    bool setNonBlocking(SOCKET s, bool nb);
};
 
#endif // SOCKET_COMM_H