UDPSocket - UDPソケット
UDPSocket - UDPソケット
UDP/IPデータグラム型ソケットで通信します。
EthernetNetIf をインポートして使用する。
初期化
UDPSocket name;
name:任意の名前
ソケットへのアドレスの割り当て
ret = name.bind(host);
host:割り当てるアドレス・ポート (Host)
ret:エラーコード (UDPSocketErr)
コネクションレス送信
ret = name.sendto(buf, len, remote);
buf:送信データのポインター (char *)
len:送信するバイト数 (int)
remote:送信先のアドレス・ポート (Host *)
ret:送信したバイト数 (int)
コネクションレス受信
ret = name.recvfrom(buf, len, remote);
buf:受信データバッファのポインター (char *)
len:受信データバッファのバイト数 (int)
remote:送信先のアドレス・ポート (Host *)
ret:受信したバイト数 (int)
コールバックの設定
name.setOnEvent(fptr)
fptr: コールバック処理関数のポインタ (void (*pMethod)(UDPSocketEvent))
例
UDPサーバ
#include "mbed.h"
#include "EtnernetNetIf.h"
#include "UDPSocket.h"
EtnernetNetIf eth;
UDPSocket sock;
void onUDPSocketEvent (e) {
Host client;
char buf[100];
int i;
if (e == UDPSOCKET_READABLE) { // 受信
i = sock.recvfrom(buf, sizeof(buf), &client);
buf[i] = 0;
printf("Connected from %d.%d.%d.%d\r\n", (unsigned char)client->getIp()[0], (unsigned char)client->getIp()[1], (unsigned char)client->getIp()[2], (unsigned char)client->getIp()[3]);
printf("%s\r\n", buf);
}
}
int main () {
Host local(IpAddr(192,168,0,10), 1234);
if (eth.setup()) {
return -1;
}
sock.setOnEvent(&onUDPSocketEvent);
if (sock.bind(local) != UDPSOCKET_OK) {
return -1;
}
while (1) {
Net::poll();
}
}
UDPクライアント
#include "mbed.h"
#include "EtnernetNetIf.h"
#include "UDPSocket.h"
EtnernetNetIf eth;
TCPSocket sock;
int main () {
Host server(IpAddr(192,168,0,10), 1234);
if (eth.setup()) {
return -1;
}
sock.sendto("Hello World!", 12, &server); // 送信
while (1) {
Net::poll();
}
}
Please log in to post comments.
