| Unity Transport | 0.2.4-preview.0
docs.unity3d.com
    Show / Hide Table of Contents
    using UnityEngine;
    
    using Unity.Collections;
    using Unity.Networking.Transport;
    
    public class ClientBehaviour : MonoBehaviour
    {
        public UdpNetworkDriver m_Driver;
        public NetworkConnection m_Connection;
        public bool m_Done;
    
        void Start ()
        {
            m_Driver = new UdpNetworkDriver(new INetworkParameter[0]);
            m_Connection = default(NetworkConnection);
    
            var endpoint = NetworkEndPoint.LoopbackIpv4;
            endpoint.Port = 9000;
            m_Connection = m_Driver.Connect(endpoint);
        }
    
        public void OnDestroy()
        {
            m_Driver.Dispose();
        }
    
        void Update()
        {
            m_Driver.ScheduleUpdate().Complete();
    
            if (!m_Connection.IsCreated)
            {
                if (!m_Done)
                    Debug.Log("Something went wrong during connect");
                return;
            }
    
            DataStreamReader stream;
            NetworkEvent.Type cmd;
    
            while ((cmd = m_Connection.PopEvent(m_Driver, out stream)) !=
                   NetworkEvent.Type.Empty)
            {
                if (cmd == NetworkEvent.Type.Connect)
                {
                    Debug.Log("We are now connected to the server");
    
                    var value = 1;
                    using (var writer = new DataStreamWriter(4, Allocator.Temp))
                    {
                        writer.Write(value);
                        m_Connection.Send(m_Driver, writer);
                    }
                }
                else if (cmd == NetworkEvent.Type.Data)
                {
                    var readerCtx = default(DataStreamReader.Context);
                    uint value = stream.ReadUInt(ref readerCtx);
                    Debug.Log("Got the value = " + value + " back from the server");
                    m_Done = true;
                    m_Connection.Disconnect(m_Driver);
                    m_Connection = default(NetworkConnection);
                }
                else if (cmd == NetworkEvent.Type.Disconnect)
                {
                    Debug.Log("Client got disconnected from server");
                    m_Connection = default(NetworkConnection);
                }
            }
        }
    }
    
    Back to top
    Copyright © 2023 Unity Technologies — Terms of use
    • Legal
    • Privacy Policy
    • Cookies
    • Do Not Sell or Share My Personal Information
    • Your Privacy Choices (Cookie Settings)
    "Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
    Generated by DocFX on 18 October 2023