LoginSignup
1
1

More than 3 years have passed since last update.

Unityで2つのアプリをUDPでローカル通信させる

Posted at

はじめ

デュアルモニターで2つのアプリを起動。
片方をお客様用。片方はスタッフ用のような使い方を前提にしています。

コード

UDPマネージャー

UdpManager.ts
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;

namespace Model.UserDatagrams
{
    public class UdpManager : MonoBehaviour
    {
        public delegate void Callback(UdpData udpData);

        private Callback _callbacks;

        public void AddCallback(Callback callback)
        {
            _callbacks += callback;
        }

        private const string Host = "localHost";
        private const int ReceivePort = 10011;
        private const int SendPort = 10012;
        private const string AppType = "app01";
        private UdpClient _client;
        private Thread _thread;

        private void Start()
        {
            _client = new UdpClient();
            _client.Connect(Host, SendPort);
            _thread = new Thread(Receive) {IsBackground = true};
            _thread.Start();
        }

        /// <summary>
        /// UDPで送信
        /// </summary>
        /// <param name="text">送信コメント</param>
        public void Send(string text)
        {
            var data = new UdpData()
            {
                AppType = AppType,
                Text = text
            };
            var json = JsonUtility.ToJson(data, true);
            var dgram = Encoding.UTF8.GetBytes(json);
            _client.Send(dgram, dgram.Length);
        }

        private void Receive()
        {
            var receiver = new UdpClient(ReceivePort);
            //古い書き方のかなぁ。エラーが出る。
            //receiver.Client.ReceiveTimeout = 1000;
            while (true)
            {
                try
                {
                    IPEndPoint anyIp = null;
                    var bytesData = receiver.Receive(ref anyIp);
                    var text = Encoding.UTF8.GetString(bytesData);
                    var udpData = JsonUtility.FromJson<UdpData>(text);
                    _callbacks(udpData);
                }
                catch (Exception err)
                {
                    Debug.Log("catch :" + err);
                }
            }
            // ReSharper disable once FunctionNeverReturns
        }
        private void OnApplicationQuit()
        {
            _thread.Abort();
        }
    }
}




git
https://github.com/kawamurashin/UnityUDPManagerTest

サンプルアプリ

Git https://github.com/kawamurashin/UnityUdpManagerApp1

片方だけのアプリだけでは操作できないように、両アプリ起動をコントロールします。

アプリ起動後の準備中として相手のアプリの状況を確認します。。
準備中は、文字列"ready"を受信したら、"ready"を送り返すようにします。

そしてまず、こちらから"ready"という文字列を送ります。
なにも帰ってこなければ、相手アプリは起動してないので準備中のままにします。
文字列"ready"が帰ってくれば、相手アプリは起動しているので、システム開始します。

その後の準備中に"ready"が送り返されたら、相手アプリが起動したということです。
文字列"ready"を送り、システム開始します。

まとめ

とりあえず通信はできました。
送受信に2つのPortを用意しないでめでした。
もう少しスマートになるのかしらね。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1