static void OnAppIdle(object sender, EventArgs e)
        {
            while (NativeMethods.AppStillIdle)
            {
                NetMessageType type;
                if (m_client.ReadMessage(m_readBuffer, out type))
                {
                    switch (type)
                    {
                    case NetMessageType.ServerDiscovered:
                        IPEndPoint ep = m_readBuffer.ReadIPEndPoint();
                        m_client.Connect(ep);
                        break;

                    case NetMessageType.Receipt:
                        NativeMethods.AppendText(m_mainForm.richTextBox1, "Got receipt for packet sized " + m_readBuffer.ReadInt32());
                        if (m_client.Status == NetConnectionStatus.Connected)
                        {
                            m_nextSize *= 2;
                            if (m_nextSize > 1000000)
                            {
                                // 1 meg message is enough
                                NativeMethods.AppendText(m_mainForm.richTextBox1, "Done");
                                m_client.Disconnect("Done");
                                return;
                            }
                            SendPacket();
                        }
                        break;

                    case NetMessageType.VerboseDebugMessage:
                    case NetMessageType.DebugMessage:
                    case NetMessageType.BadMessageReceived:
                        NativeMethods.AppendText(m_mainForm.richTextBox1, m_readBuffer.ReadString());
                        break;

                    case NetMessageType.StatusChanged:
                        if (m_client.Status == NetConnectionStatus.Connected)
                        {
                            m_nextSize = 8;
                            SendPacket();
                        }
                        break;
                    }
                }

                if (m_client != null && m_client.ServerConnection != null)
                {
                    m_mainForm.Text = m_client.ServerConnection.Statistics.CurrentlyUnsentMessagesCount + " unsent messages";
                }

                if (NetTime.Now > s_nextDisplay)
                {
                    m_mainForm.label1.Text = m_client.GetStatisticsString(m_client.ServerConnection);
                    s_nextDisplay          = NetTime.Now + 0.2;            // five times per second
                }

                System.Threading.Thread.Sleep(1);
            }
        }
Exemple #2
0
        private void OnUnconnectedDataReceived(IPEndPoint endpoint, NetBuffer incomingData)
        {
            if (endpoint.Equals(_natFacilitatorEndpoint))
            {
                var messageType = (NatFacilitatorMessageType)incomingData.ReadByte();
                switch (messageType)
                {
                case NatFacilitatorMessageType.HostNotRegistered:
                    // Handle host not registered response
                    if (OnNatPunchFailure != null)
                    {
                        var punchId = new NatPunchId(incomingData.ReadString());
                        OnNatPunchFailure(punchId, endpoint);
                    }
                    break;

                case NatFacilitatorMessageType.PeerRegistrationSuccess:
                    if (_isRegistrationRunning)
                    {
                        _externalEndpoint.SetResult(incomingData.ReadIPEndPoint());
                    }
                    break;

                default:
                    // Skip this message
                    break;
                }
            }
        }
Exemple #3
0
        private static void HandleMessage(NetMessageType type, NetConnection source, NetBuffer buffer)
        {
            switch (type)
            {
            case NetMessageType.StatusChanged:
                if (source.LocalHailData == null)
                {
                    source.LocalHailData = Encoding.ASCII.GetBytes("Hi; I'm " + s_peer.GetHashCode());
                }
                if (source.RemoteHailData != null)
                {
                    WriteToConsole("New status: " + source.Status + " - remote hail is: " + Encoding.ASCII.GetString(source.RemoteHailData));
                }
                else
                {
                    WriteToConsole("New status: " + source.Status + " - remote hail is null");
                }
                break;

            case NetMessageType.DebugMessage:
            case NetMessageType.VerboseDebugMessage:
            case NetMessageType.BadMessageReceived:
            case NetMessageType.ConnectionRejected:
                WriteToConsole(buffer.ReadString());
                break;

            case NetMessageType.Data:
                WriteToConsole(source.RemoteEndpoint + " writes: " + buffer.ReadString());
                break;

            case NetMessageType.ServerDiscovered:
                // discovered another peer!
                s_peer.Connect(buffer.ReadIPEndPoint(), Encoding.ASCII.GetBytes("Hi; I'm " + s_peer.GetHashCode()));
                break;

            default:
                // unhandled
                break;
            }
        }
Exemple #4
0
        internal void Deserialize(NetBuffer buffer)
        {
            try
            {
                _fields = new Dictionary <string, Pair <DataType, object> >();

                while (true)
                {
                    string key = buffer.ReadString();
                    if (string.IsNullOrEmpty(key))
                    {
                        break;
                    }

                    DataType type = (DataType)buffer.ReadByte();
                    if (type == DataType.Unknown)
                    {
                        throw new Exception();
                    }

                    switch (type)
                    {
                    case DataType.Byte:
                        _fields.Add(key, new Pair <DataType, object>(type, buffer.ReadByte()));
                        break;

                    case DataType.Ushort:
                        _fields.Add(key, new Pair <DataType, object>(type, buffer.ReadUInt16()));
                        break;

                    case DataType.Uint:
                        _fields.Add(key, new Pair <DataType, object>(type, buffer.ReadUInt32()));
                        break;

                    case DataType.Ulong:
                        _fields.Add(key, new Pair <DataType, object>(type, buffer.ReadUInt64()));
                        break;

                    case DataType.Sbyte:
                        _fields.Add(key, new Pair <DataType, object>(type, buffer.ReadSByte()));
                        break;

                    case DataType.Short:
                        _fields.Add(key, new Pair <DataType, object>(type, buffer.ReadInt16()));
                        break;

                    case DataType.Int:
                        _fields.Add(key, new Pair <DataType, object>(type, buffer.ReadInt32()));
                        break;

                    case DataType.Long:
                        _fields.Add(key, new Pair <DataType, object>(type, buffer.ReadInt64()));
                        break;

                    case DataType.String:
                        _fields.Add(key, new Pair <DataType, object>(type, buffer.ReadString()));
                        break;

                    case DataType.Double:
                        _fields.Add(key, new Pair <DataType, object>(type, buffer.ReadDouble()));
                        break;

                    case DataType.Float:
                        _fields.Add(key, new Pair <DataType, object>(type, buffer.ReadFloat()));
                        break;

                    case DataType.Bool:
                        _fields.Add(key, new Pair <DataType, object>(type, buffer.ReadBoolean()));
                        break;

                    case DataType.IPEndPoint:
                        _fields.Add(key, new Pair <DataType, object>(type, buffer.ReadIPEndPoint()));
                        break;
                    }
                }

                Count = _fields.Count;
                Keys  = new string[_fields.Count];
                _fields.Keys.CopyTo(Keys, 0);
            }
            catch
            {
                _Empty();
            }
        }
Exemple #5
0
 public ServerInformation(NetBuffer netBuffer)
 {
     ipEndPoint = netBuffer.ReadIPEndPoint();
     serverName = ipEndPoint.Address.ToString();
     lanServer  = true;
 }
 public IPEndPoint ReadIPEndPoint()
 {
     return(_buffer.ReadIPEndPoint());
 }
Exemple #7
0
        static void Main(string[] args)
        {
            // create a client with a default configuration
            NetConfiguration config = new NetConfiguration("chatApp");
            NetClient        client = new NetClient(config);

            client.SetMessageTypeEnabled(NetMessageType.ConnectionRejected, true);
            client.SetMessageTypeEnabled(NetMessageType.DebugMessage, true);
            //client.SetMessageTypeEnabled(NetMessageType.VerboseDebugMessage, true);
            client.Start();

            // Wait half a second to allow server to start up if run via Visual Studio
            Thread.Sleep(500);

            // Emit discovery signal
            client.DiscoverLocalServers(14242);

            // create a buffer to read data into
            NetBuffer buffer = client.CreateBuffer();

            // current input string
            string input = "";

            // keep running until the user presses a key
            Console.WriteLine("Type 'quit' to exit client");
            Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
            s_keepGoing             = true;
            while (s_keepGoing)
            {
                NetMessageType type;

                // check if any messages has been received
                while (client.ReadMessage(buffer, out type))
                {
                    switch (type)
                    {
                    case NetMessageType.ServerDiscovered:
                        // just connect to any server found!

                        // make hail
                        NetBuffer buf = client.CreateBuffer();
                        buf.Write("Hail from " + Environment.MachineName);
                        client.Connect(buffer.ReadIPEndPoint(), buf.ToArray());
                        break;

                    case NetMessageType.ConnectionRejected:
                        Console.WriteLine("Rejected: " + buffer.ReadString());
                        break;

                    case NetMessageType.DebugMessage:
                    case NetMessageType.VerboseDebugMessage:
                        Console.WriteLine(buffer.ReadString());
                        break;

                    case NetMessageType.StatusChanged:
                        string statusMessage          = buffer.ReadString();
                        NetConnectionStatus newStatus = (NetConnectionStatus)buffer.ReadByte();
                        Console.WriteLine("New status: " + newStatus + " (" + statusMessage + ")");
                        break;

                    case NetMessageType.Data:
                        // The server sent this data!
                        string msg = buffer.ReadString();
                        Console.WriteLine(msg);
                        break;
                    }
                }

                while (Console.KeyAvailable)
                {
                    ConsoleKeyInfo ki = Console.ReadKey();
                    if (ki.Key == ConsoleKey.Enter)
                    {
                        if (!string.IsNullOrEmpty(input))
                        {
                            if (input == "quit")
                            {
                                // exit application
                                s_keepGoing = false;
                            }
                            else
                            {
                                // Send chat message
                                NetBuffer sendBuffer = new NetBuffer();
                                sendBuffer.Write(input);
                                client.SendMessage(sendBuffer, NetChannel.ReliableInOrder1);
                                input = "";
                            }
                        }
                    }
                    else
                    {
                        input += ki.KeyChar;
                    }
                }

                Thread.Sleep(1);
            }

            client.Shutdown("Application exiting");
        }
        /// <summary>
        /// Handle incoming message
        /// </summary>
        private void HandleMessage(NetMessageType type, NetBuffer buffer)
        {
            switch (type)
            {
            case NetMessageType.DebugMessage:
                //
                // it's a library debug message; just display it in the console if debugger is attached
                //
                Console.WriteLine(buffer.ReadString());
                break;

            case NetMessageType.StatusChanged:
                //
                // it's a status change message; set the reason as window title and refresh picture
                //
                this.Text = buffer.ReadString();
                pictureBox1.Refresh();
                break;

            case NetMessageType.ServerDiscovered:
                //
                // it's a server discovered message; connect to the discovered server
                //
                m_imageWidth    = 0;
                m_imageHeight   = 0;
                m_lineDisplayed = 0;

                m_client.Connect(buffer.ReadIPEndPoint());
                break;

            case NetMessageType.Data:
                //
                // it's a data message (data sent from the server)
                //
                if (m_imageWidth == 0)
                {
                    // first message is size
                    m_imageWidth      = (int)buffer.ReadVariableUInt32();
                    m_imageHeight     = (int)buffer.ReadVariableUInt32();
                    this.Size         = new System.Drawing.Size(m_imageWidth + 40, m_imageHeight + 60);
                    pictureBox1.Image = new Bitmap(m_imageWidth, m_imageHeight);
                    pictureBox1.SetBounds(12, 12, m_imageWidth, m_imageHeight);
                    return;
                }

                uint pixelPos = buffer.ReadUInt32();

                // it's color data
                int y = (int)(pixelPos / m_imageWidth);
                int x = (int)(pixelPos - (y * m_imageWidth));

                Bitmap bm = pictureBox1.Image as Bitmap;
                pictureBox1.SuspendLayout();
                int pixels = (buffer.LengthBytes - 4) / 3;
                for (int i = 0; i < pixels; i++)
                {
                    // set pixel
                    byte  r   = buffer.ReadByte();
                    byte  g   = buffer.ReadByte();
                    byte  b   = buffer.ReadByte();
                    Color col = Color.FromArgb(r, g, b);
                    if (y > m_imageHeight)
                    {
                        continue;
                    }
                    bm.SetPixel(x, y, col);
                    x++;
                    if (x >= m_imageWidth)
                    {
                        x = 0;
                        y++;
                    }
                }
                pictureBox1.ResumeLayout();

                // refresh image every horizontal line
                if (pixelPos / m_imageWidth > m_lineDisplayed)
                {
                    m_lineDisplayed = (int)(pixelPos / m_imageWidth);
                    pictureBox1.Refresh();
                }
                break;

            default:
                // unhandled
                break;
            }
        }
Exemple #9
0
        public static void Main(string[] args)
        {
            setupNetwork();

            // create a buffer to read data into
            NetBuffer buffer = client.CreateBuffer();

            s_keepGoing = true;
            while (s_keepGoing)
            {
                NetMessageType type;



                // check if any messages has been received
                while (client.ReadMessage(buffer, out type))
                {
                    switch (type)
                    {
                    case NetMessageType.ServerDiscovered:
                        // just connect to any server found!

                        // make hail
                        NetBuffer buf = client.CreateBuffer();
                        buf.Write("Hail from " + Environment.MachineName);
                        client.Connect(buffer.ReadIPEndPoint(), buf.ToArray());
                        break;

                    case NetMessageType.ConnectionRejected:
                        Console.WriteLine("Rejected: " + buffer.ReadString());
                        break;

                    case NetMessageType.DebugMessage:
                    case NetMessageType.VerboseDebugMessage:
                        Console.WriteLine(buffer.ReadString());
                        break;

                    case NetMessageType.StatusChanged:
                        string statusMessage = buffer.ReadString();
                        Console.WriteLine("New status:   (" + statusMessage + ")");
                        break;

                    case NetMessageType.Data:
                        // The server sent this data!
                        string msg = buffer.ReadString();
                        Console.WriteLine(msg);
                        break;
                    }
                }


                update();

                if (client.Status == NetConnectionStatus.Connected)
                {
                    NetBuffer sendBuffer = new NetBuffer();
                    sendBuffer.Write(" ApacheNetworkObject:VBS2:foo:" + _x + ":" + _y + ":" + _z + ":" + _pitch + ":" + _yaw + ":" + _roll);
                    client.SendMessage(sendBuffer, NetChannel.ReliableInOrder14);
                }
                else
                {
                    Console.Out.WriteLine("Client lost connection....");
                    s_keepGoing = false;
                }

                Thread.Sleep(10);
            }

            client.Shutdown("Application exiting");
        }
 public void Deserialize(NetBuffer reader)
 {
     Token    = reader.ReadString();
     Endpoint = reader.ReadIPEndPoint();
 }