Created
          April 20, 2023 21:39 
        
      - 
      
- 
        Save yohawing/0c4884b862b33064305a853bebe56c6d to your computer and use it in GitHub Desktop. 
    Winsock2 Simple UDP Client CPP
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | #pragma once | |
| #include <stdio.h> | |
| #include <string> | |
| #include <WinSock2.h> | |
| #include <WS2tcpip.h> | |
| using namespace std; | |
| class UDPClient | |
| { | |
| public: | |
| string ipAddress; | |
| int port; | |
| int sock; | |
| struct sockaddr_in addr; | |
| UDPClient(string _ipAddress, int _port) { | |
| ipAddress = _ipAddress; | |
| port = _port; | |
| } | |
| void init() { | |
| WSAData wsaData; | |
| WSACleanup(); | |
| WSAStartup(MAKEWORD(2, 0), &wsaData); | |
| sock = socket(AF_INET, SOCK_DGRAM, 0); | |
| addr.sin_port = htons(port); | |
| addr.sin_family = AF_INET; | |
| inet_pton(addr.sin_family, ipAddress.c_str(), &addr.sin_addr.s_addr); | |
| bind(sock, (struct sockaddr*)&addr, sizeof(addr)); | |
| } | |
| size_t send(char* buffer, size_t size) { | |
| sendto(sock, buffer, size, 0, (struct sockaddr*)&addr, sizeof(addr)); | |
| printf("send data size: %d\n", size); | |
| return size; | |
| } | |
| void close() { | |
| closesocket(sock); | |
| WSACleanup(); | |
| } | |
| }; | |
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
oscpp sample