-
-
Save Maximilian-Winter/cb5d65d6e404db4c60394e817869e44f to your computer and use it in GitHub Desktop.
HoloLens用UDP受信プログラム(ClientじゃなくてServerかな)
This file contains 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
using UnityEngine; | |
using UnityEngine.Assertions; | |
using System.Text; | |
#if UNITY_EDITOR | |
using System.Net; | |
using System.Net.Sockets; | |
#else | |
using System; | |
using System.IO; | |
using Windows.Networking.Sockets; | |
#endif | |
public class UDPClientUWP : MonoBehaviour | |
{ | |
[SerializeField] | |
int listenPort = 3333; | |
void OnMessage(string msg) | |
{ | |
//ここでメッセージの処理 | |
Debug.Log("I Receive " + msg); | |
} | |
#if UNITY_EDITOR | |
UdpClient udpClient; | |
IPEndPoint endPoint; | |
void Start() | |
{ | |
Debug.Log("UnityStart"); | |
endPoint = new IPEndPoint(IPAddress.Any, listenPort); | |
udpClient = new UdpClient(endPoint); | |
} | |
void Update() | |
{ | |
while (udpClient.Available > 0) { | |
var data = udpClient.Receive(ref endPoint); | |
OnMessage(Encoding.ASCII.GetString(data)); | |
} | |
} | |
#else | |
DatagramSocket socket; | |
object lockObject = new object(); | |
const int MAX_BUFFER_SIZE = 1024; | |
async void Start() | |
{ | |
Debug.Log("Start"); | |
try { | |
socket = new DatagramSocket(); | |
socket.MessageReceived += OnMessage; | |
await socket.BindServiceNameAsync(listenPort.ToString()); | |
} catch (System.Exception e) { | |
Debug.LogError(e.ToString()); | |
} | |
} | |
void Update() | |
{ | |
} | |
async void OnMessage(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) | |
{ | |
using (var stream = args.GetDataStream().AsStreamForRead()) { | |
byte[] buffer = new byte[MAX_BUFFER_SIZE]; | |
await stream.ReadAsync(buffer, 0, MAX_BUFFER_SIZE); | |
lock (lockObject) { | |
OnMessage(Encoding.ASCII.GetString(buffer)); | |
} | |
} | |
} | |
#endif | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi