Assets.UDP.Assign C# (CSharp) Method

Assign() public method

public Assign ( int portIn = -1 ) : int
portIn int
return int
        public int Assign(int portIn = -1)
        {
            //Setup the socket and message buffer
            udpSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            bool fileFound = false;

            List<string> fileNameVec = FileSystem.ListFilesInDirectory(Globals.IpcPath);
            foreach (string fileNameCurrent in fileNameVec)
                if (fileNameCurrent == "udp_port")
                {
                    fileFound = true;
                    break;
                }

            int portCurrent;

            if (fileFound)
            {
                string udpPortStr = FileSystem.ReadTextFile(Globals.IpcPath + "\\udp_port")[0];
                int.TryParse(udpPortStr, out portCurrent);
                endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), portCurrent);
            }
            else
            {
                if (portIn == -1)
                    endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 0);
                else
                    endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), portIn);
            }

            udpSock.Bind(endPoint);
            int.TryParse(udpSock.LocalEndPoint.ToString().Split(':')[1], out portCurrent);
            FileSystem.WriteStringToFile(Globals.IpcPath + "\\" + "udp_port", portCurrent.ToString());

            buffer = new byte[1024];

            //Start listening for a new message.
            udpSock.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref endPoint, DoReceiveFrom, udpSock);

            return portCurrent;
        }

Usage Example

Example #1
0
        public IPC(string selfNameIn)
        {
            selfName = selfNameIn;

            MapFunction("open udp channel", delegate(string messageBody)
            {
                if (messageBody == "")
                {
                    int port = udp.Assign();
                    SendMessage("track_plus", "open udp channel", port.ToString());
                    Globals.WriteLine("bound to UDP port " + port);
                }
                else
                {
                    int port;
                    int.TryParse(messageBody, out port);
                    udp.Assign(port);
                    Globals.WriteLine("bound to UDP port " + port);
                }
                return(1);
            });

            Update();
        }