-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathudp.h
69 lines (56 loc) · 1.66 KB
/
udp.h
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//kal Ubuntu用UDP通信ライブラリ
//受信時は制御ループの前にudp_bind()
#ifndef ___KAL_UDP_H
#define ___KAL_UDP_H
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include "config.h"
namespace kal{
template<class T>
class udp{
int sock;
struct sockaddr_in addr;
public:
T data;//送るデータの方を事前に決めとく
udp(std::string address, int port){
sock = socket(AF_INET, SOCK_DGRAM, 0);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(address.c_str());
addr.sin_port = htons(port);
}
void string_send(std::string word){//文字列を送る
sendto(sock, word.c_str(), word.length(), 0, (struct sockaddr *)&addr, sizeof(addr));
}
void send(T buf){//T型のオブジェクトを送る
sendto(sock, &buf, sizeof(buf), 0, (struct sockaddr *)&addr, sizeof(addr));
}
void udp_bind(){//受信状態にする
bind(sock, (const struct sockaddr *)&addr, sizeof(addr));
}
std::string string_recv(){//文字列を受け取る:w
#define BUFFER_MAX 400
char buf[BUFFER_MAX];
memset(buf, 0, sizeof(buf));
recv(sock, buf, sizeof(buf), 0);
return std::string(buf);
}
void string_recv(char *buf, int size){
memset(buf, 0, size);
recv(sock, buf, size, 0);
}
T receive(){//T型のオブジェクトを受け取る
memset(&data, 0, sizeof(data));
recv(sock, &data, sizeof(data), 0);
return data;
}
~udp(){
close(sock);
}
};
}
#endif