Пример #1
0
        private void SendRegisteredMessage(int clientId)
        {
            try
            {
                var xdata = new PacketData
                {
                    Packet_Type = (ushort)PacketTypes.Registered,
                    Data_Type   = 0,
                    Packet_Size = (ushort)Marshal.SizeOf(typeof(PacketData)),
                    maskTo      = 0,
                    idTo        = 0,
                    idFrom      = (uint)clientId,
                    Data6       = System.Reflection.Assembly.GetEntryAssembly().GetName().Version.Major,
                    Data7       = System.Reflection.Assembly.GetEntryAssembly().GetName().Version.Minor,
                    Data8       = System.Reflection.Assembly.GetEntryAssembly().GetName().Version.Build
                };

                var byData = PacketFunctions.StructureToByteArray(xdata);
                _svr.SendMessage(byData);
            }
            catch
            {
                // ignored
            }
        }
Пример #2
0
        public static void SendAUTH(Socket s, int idx, int token, byte hero_order, string username)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                int len = 0;
                using (BinaryWriter bw = new BinaryWriter(ms, Encoding.UTF8))
                {
                    Console.WriteLine("IDX: " + idx + " TOken: " + token + " HeroOrder: " + hero_order + " Username: " + username);

                    bw.Write((int)Conn.ZoneServer.base_key); // token
                    bw.Write((int)idx);
                    bw.Write((byte)hero_order);
                    bw.Write((byte)100); // packet type
                    bw.Write((int)idx);
                    bw.Write((int)token);
                    bw.Write((byte)0x00);
                    foreach (char c in username)
                    {
                        bw.Write((byte)c);
                    }
                    bw.Write(new byte[] { 0x00, 0xBF, 0xB5, 0xC8, 0xF1, 0x00 });

                    len = (int)bw.BaseStream.Length;
                }
                byte[] buffer = ms.GetBuffer();
                Array.Resize(ref buffer, len);
                PacketFunctions.ZSMakePacketAndSend(s, buffer);
            }
        }
Пример #3
0
        public static void SendGlobal(Socket s, string message)
        {
            if (message.Length >= 48)
            {
                Console.WriteLine("[Global] Message is big"); return;
            }
            using (MemoryStream ms = new MemoryStream())
            {
                int len = 0;
                using (BinaryWriter bw = new BinaryWriter(ms, Encoding.UTF8))
                {
                    bw.Write((Int32)Conn.ZoneServer.base_key);
                    bw.Write((int)Conn.ZoneServer.id_idx);
                    bw.Write((byte)Conn.ZoneServer.hero_order);
                    bw.Write((byte)128);  // packet type
                    bw.Write((byte)0x03); // gm command id

                    // message
                    foreach (char c in message)
                    {
                        bw.Write((byte)c);
                    }

                    bw.Write((byte)0x00);

                    len = (int)bw.BaseStream.Length;
                }
                byte[] buffer = ms.GetBuffer();
                Array.Resize(ref buffer, len);
                PacketFunctions.ZSMakePacketAndSend(s, buffer);
            }
        }
Пример #4
0
    public void ConnectToServer()
    {
        debugTextField.text = "";

        string ip = serverIP.text;

        if (!m_Connection.IsCreated || lastIP != ip)
        {
            if (m_Connection.IsCreated)
            {
                m_Connection.Disconnect(m_Driver);
                m_Connection = default(NetworkConnection);
            }

            lastIP = ip;
            if (ip == "")
            {
                ip = "127.0.0.1";
            }
            var endpoint = NetworkEndPoint.Parse(ip, 9000);
            m_Connection = m_Driver.Connect(endpoint);
        }
        else
        {
            //send message for new hello
            using (var writer = PacketFunctions.WritePacket(GameEvent.HELLO_SERVER)) {
                //m_Connection.Send(m_Driver, writer);
                m_Connection.Send(m_Driver, reliableUdpPipe, writer);
            }
        }
    }
Пример #5
0
        public static void SelectEnterGameCharacter(Socket s, int idx, string hero_name, byte hero_order)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                int len = 0;

                byte[] hero_namebytes = new byte[13];
                for (int i = 0; i < hero_name.Length; i++)
                {
                    hero_namebytes[i] = (byte)hero_name[i];
                }
                using (BinaryWriter bw = new BinaryWriter(ms, Encoding.UTF8))
                {
                    bw.Write((Int32)idx);
                    bw.Write((byte)0x00);
                    bw.Write((byte)0x06);
                    bw.Write((byte)hero_order);
                    bw.Write(hero_namebytes);
                    len = (int)bw.BaseStream.Length;
                }
                byte[] buffer = ms.GetBuffer();
                Array.Resize(ref buffer, len);
                PacketFunctions.GMSMakePacketAndSend(s, buffer);
            }
        }
Пример #6
0
        public static void SendLogin(Socket s, string Username, string Password)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                int len = 0;

                // user
                byte[] user_bytes = new byte[21];
                for (int i = 0; i < Username.Length; i++)
                {
                    user_bytes[i] = (byte)Username[i];
                }
                // pass
                byte[] pass_bytes = new byte[21];
                for (int i = 0; i < Password.Length; i++)
                {
                    pass_bytes[i] = (byte)Password[i];
                }


                using (BinaryWriter bw = new BinaryWriter(ms, Encoding.UTF8))
                {
                    bw.Write((byte)21); // packet
                    bw.Write(user_bytes);
                    bw.Write(pass_bytes);
                    len = (int)bw.BaseStream.Length;
                }
                byte[] buffer = ms.GetBuffer();
                Array.Resize(ref buffer, len);
                PacketFunctions.MakePacketAndSend(s, buffer);
            }
        }
Пример #7
0
 public static void SendInitial(Socket s, int idx, int token, string username)
 {
     using (MemoryStream ms = new MemoryStream())
     {
         int    len        = 0;
         byte[] user_bytes = new byte[32];
         for (int i = 0; i < username.Length; i++)
         {
             user_bytes[i] = (byte)username[i];
         }
         using (BinaryWriter bw = new BinaryWriter(ms, Encoding.UTF8))
         {
             bw.Write((Int32)idx);
             bw.Write((byte)0x00);
             bw.Write((byte)0x00);    // packet type
             bw.Write((float)15.04f); // exe_ver
             bw.Write((Int32)idx);
             bw.Write((Int32)token);
             bw.Write(user_bytes);
             len = (int)bw.BaseStream.Length;
         }
         byte[] buffer = ms.GetBuffer();
         Array.Resize(ref buffer, len);
         PacketFunctions.GMSMakePacketAndSend(s, buffer);
     }
 }
Пример #8
0
        private static void ParseLoginResponse(Socket s, byte[] body)
        {
            using (MemoryStream stream = new MemoryStream(body))
            {
                using (BinaryReader br = new BinaryReader(stream, Encoding.UTF8))
                {
                    br.ReadByte(); // packet type
                    br.ReadByte(); // gms server count
                    br.ReadByte();
                    byte[] server_namebuff = br.ReadBytes(16);
                    br.ReadByte();
                    short players_online = br.ReadInt16();
                    br.ReadByte();
                    byte[] gms_ipbuff = br.ReadBytes(15);
                    br.ReadByte();
                    short gms_port = br.ReadInt16();


                    string gms_ip = PacketFunctions.ExtractStringFromBytes(gms_ipbuff);

                    LoginServer.GMS_IP   = gms_ip;
                    LoginServer.GMS_PORT = gms_port;
                    Console.WriteLine("Servername: " + gms_ip);
                    Console.WriteLine("Players Online: " + players_online);
                    Console.WriteLine("GMS: " + PacketFunctions.ExtractStringFromBytes(gms_ipbuff) + ":" + gms_port);
                }
            }
        }
Пример #9
0
    void Update()
    {
        m_Driver.ScheduleUpdate().Complete();

        if (!m_Connection.IsCreated)
        {
            if (!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");

                using (var writer = PacketFunctions.WritePacket(GameEvent.HELLO_SERVER)) {
                    //m_Connection.Send(m_Driver, writer);
                    m_Connection.Send(m_Driver, reliableUdpPipe, writer);
                }

                /*
                 * 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)
            {
                //read received packet
                DataStreamReader.Context readerCtx = default(DataStreamReader.Context);
                PacketFunctions.ReadPacket(stream, ref readerCtx, PushToScreen);

                /*
                 * // var readerCtx = default(DataStreamReader.Context);
                 * uint value = stream.ReadUInt(ref readerCtx);
                 * Debug.Log("Got the value = " + value + " back from the server");
                 * 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);
            }
        }
    }
Пример #10
0
    // Update is called once per frame
    void Update()
    {
        m_Driver.ScheduleUpdate().Complete();

        // Clean up connections
        for (int i = 0; i < m_Connections.Length; i++)
        {
            if (!m_Connections[i].IsCreated)
            {
                m_Connections.RemoveAtSwapBack(i);
                --i;
            }
        }

        // Accept new connections
        NetworkConnection c;

        while ((c = m_Driver.Accept()) != default(NetworkConnection))
        {
            m_Connections.Add(c);
            Debug.Log("Accepted a connection");
        }

        DataStreamReader stream;

        for (int i = 0; i < m_Connections.Length; i++)
        {
            if (!m_Connections[i].IsCreated)
            {
                continue;
            }

            NetworkEvent.Type cmd;
            while ((cmd = m_Driver.PopEventForConnection(m_Connections[i], out stream)) !=
                   NetworkEvent.Type.Empty)
            {
                if (cmd == NetworkEvent.Type.Data)
                {
                    //read received packet
                    DataStreamReader.Context readerCtx = default(DataStreamReader.Context);
                    PacketFunctions.ReadPacket(stream, ref readerCtx);

                    StartCoroutine(SendHelloClient(m_Connections[i]));

                    /*
                     * var readerCtx = default(DataStreamReader.Context);
                     * uint number = stream.ReadUInt(ref readerCtx);
                     * using (var writer = new DataStreamWriter(4, Allocator.Temp))
                     * {
                     *  writer.Write(number);
                     *  //other option
                     *  //m_Connections[i].Send(m_Driver, writer);
                     *  m_Driver.Send(NetworkPipeline.Null, m_Connections[i], writer);
                     * }
                     */
                }
            }
        }
    }
Пример #11
0
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_svr != null)
            {
                var xdata = new PacketData
                {
                    Packet_Type = (ushort)PacketTypes.HostExiting,
                    Data_Type   = 0,
                    Packet_Size = 16,
                    maskTo      = 0,
                    idTo        = 0,
                    idFrom      = 0
                };

                var byData = PacketFunctions.StructureToByteArray(xdata);

                _svr.SendMessage(byData);

                Thread.Sleep(250);
            }

            _serverIsExiting = true;
            try
            {
                if (_timerGarbagePatrol != null)
                {
                    _timerGarbagePatrol.Stop();
                    _timerGarbagePatrol.Elapsed -= timerGarbagePatrol_Elapsed;
                    _timerGarbagePatrol.Dispose();
                    _timerGarbagePatrol = null;
                }
            }
            catch
            {
                // ignored
            }

            try
            {
                if (_timerPing != null)
                {
                    _timerPing.Stop();
                    _timerPing.Elapsed -= timerPing_Elapsed;
                    _timerPing.Dispose();
                    _timerPing = null;
                }
            }
            catch
            {
                // ignored
            }

            KillTheServer();
        }
Пример #12
0
 IEnumerator SendHelloClient(NetworkConnection c)
 {
     for (int x = 0; x < 512; ++x)
     {
         using (var writer = PacketFunctions.WriteHelloClientPacket()) {
             //m_Driver.Send(reliableUdpPipe, c, writer);
             m_Driver.Send(NetworkPipeline.Null, c, writer);
         }
         yield return(null);
     }
 }
Пример #13
0
        void PingTheConnections()
        {
            if (_svr == null)
            {
                return;
            }

            try
            {
                var xdata = new PacketData();

                xdata.Packet_Type = (ushort)PacketTypes.Ping;
                xdata.Data_Type   = 0;
                xdata.Packet_Size = 16;
                xdata.maskTo      = 0;
                xdata.idTo        = 0;
                xdata.idFrom      = 0;

                xdata.DataLong1 = DateTime.UtcNow.Ticks;

                var byData = PacketFunctions.StructureToByteArray(xdata);

                //Stopwatch sw = new Stopwatch();

                //sw.Start();
                lock (_svr.WorkerSockets)
                {
                    foreach (var s in _svr.WorkerSockets.Values)
                    {
                        //Console.WriteLine("Ping id - " + s.iClientID.ToString());
                        //Thread.Sleep(25);//allow a slight moment so all the replies dont happen at the same time
                        s.PingStatClass.StartTheClock();

                        try
                        {
                            _svr.SendMessage(s.ClientId, byData);
                        }
                        catch
                        {
                            // ignored
                        }
                    }
                }

                //sw.Stop();
                //Debug.WriteLine("TimeAfterSend: " + sw.ElapsedMilliseconds.ToString() + "ms");
            }
            catch
            {
                // ignored
            }
        }
Пример #14
0
        private void AssembleMessage(int clientId, byte[] message)
        {
            try
            {
                var incomingData = (PacketData)PacketFunctions.ByteArrayToStructure(message, typeof(PacketData));

                switch (incomingData.Data_Type)
                {
                case (ushort)PacketTypesSubMessage.Start:
                {
                    if (_svr.WorkerSockets.ContainsKey(clientId))
                    {
                        OnCommunications(
                            $"Client '{_svr.WorkerSockets[clientId].SzClientName}' sent some numbers and some text... num1= {incomingData.Data16} and num2= {incomingData.Data17}:",
                            Ink.ClrBlue);
                        OnCommunications($"Client also said:", Ink.ClrBlue);
                        OnCommunications(new string(incomingData.szStringDataA).TrimEnd('\0'), Ink.ClrGreen);
                    }
                }
                break;

                case (ushort)PacketTypesSubMessage.Guts:
                {
                    OnCommunications(new string(incomingData.szStringDataA).TrimEnd('\0'), Ink.ClrGreen);
                }
                break;

                case (ushort)PacketTypesSubMessage.End:
                {
                    OnCommunications("FINISHED GETTING MESSAGE", Ink.ClrBlue);

                    /****************************************************************/
                    //Now tell the client teh message was received!
                    var xdata = new PacketData {
                        Packet_Type = (ushort)PacketTypes.MessageReceived
                    };


                    var byData = PacketFunctions.StructureToByteArray(xdata);

                    _svr.SendMessage(clientId, byData);
                }
                break;
                }
            }
            catch
            {
                Console.WriteLine(@"ERROR Assembling message");
            }
        }
Пример #15
0
 public static void EnterServer(Socket s)
 {
     using (MemoryStream ms = new MemoryStream())
     {
         int len = 0;
         using (BinaryWriter bw = new BinaryWriter(ms, Encoding.UTF8))
         {
             bw.Write((byte)27); // packet
             bw.Write((byte)0x00);
         }
         byte[] buffer = ms.GetBuffer();
         Array.Resize(ref buffer, len);
         PacketFunctions.MakePacketAndSend(s, buffer);
     }
 }
Пример #16
0
 public static void SendVersion(Socket s, float version)
 {
     using (MemoryStream ms = new MemoryStream())
     {
         int len = 0;
         using (BinaryWriter bw = new BinaryWriter(ms, Encoding.UTF8))
         {
             bw.Write((byte)10); // packet
             bw.Write((float)version);
             len = (int)bw.BaseStream.Length;
         }
         byte[] buffer = ms.GetBuffer();
         Array.Resize(ref buffer, len);
         PacketFunctions.MakePacketAndSend(s, buffer);
     }
 }
Пример #17
0
 public static void SendListCharacters(Socket s, int idx)
 {
     using (MemoryStream ms = new MemoryStream())
     {
         int len = 0;
         using (BinaryWriter bw = new BinaryWriter(ms, Encoding.UTF8))
         {
             bw.Write((Int32)idx);
             bw.Write((byte)0x00);
             bw.Write((byte)0x02); // packet type
             len = (int)bw.BaseStream.Length;
         }
         byte[] buffer = ms.GetBuffer();
         Array.Resize(ref buffer, len);
         PacketFunctions.GMSMakePacketAndSend(s, buffer);
     }
 }
Пример #18
0
        private void RequestNewConnectionCredentials(int clientId)
        {
            try
            {
                var xdata = new PacketData
                {
                    Packet_Type = (ushort)PacketTypes.RequestCredentials,
                    Data_Type   = 0,
                    Packet_Size = 16,
                    maskTo      = 0,
                    idTo        = (ushort)clientId,
                    idFrom      = 0,
                    DataLong1   = DateTime.UtcNow.Ticks
                };


                if (!_svr.WorkerSockets.ContainsKey(clientId))
                {
                    return;
                }

                lock (_svr.WorkerSockets)
                {
                    //ship back their address for reference to the client
                    var clientAddr = ((IPEndPoint)_svr.WorkerSockets[clientId].UserSocket.RemoteEndPoint).Address
                                     .ToString();
                    clientAddr.CopyTo(0, xdata.szStringDataA, 0, clientAddr.Length);

                    var byData = PacketFunctions.StructureToByteArray(xdata);

                    if (!_svr.WorkerSockets[clientId].UserSocket.Connected)
                    {
                        return;
                    }

                    _svr.SendMessage(clientId, byData);
                    Debug.WriteLine(DateTime.Now.ToShortDateString() + ", " + DateTime.Now.ToLongTimeString() +
                                    " - from " + clientId);
                }
            }
            catch
            {
                // ignored
            }
        }
Пример #19
0
        public static void EnterGame(Socket s, int idx, byte hero_order)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                int len = 0;
                using (BinaryWriter bw = new BinaryWriter(ms, Encoding.UTF8))
                {
                    bw.Write((Int32)Conn.ZoneServer.base_key);
                    bw.Write((int)idx);
                    bw.Write((byte)hero_order);
                    bw.Write((byte)0x69);

                    len = (int)bw.BaseStream.Length;
                }
                byte[] buffer = ms.GetBuffer();
                Array.Resize(ref buffer, len);
                PacketFunctions.ZSMakePacketAndSend(s, buffer);
            }
        }
Пример #20
0
        /// <summary>
        /// return bool, TRUE if its a FullClient Connection
        /// </summary>
        /// <param name="clientNumber"></param>
        /// <param name="message"></param>
        private void PostUserCredentials(int clientNumber, byte[] message)
        {
            if (InvokeRequired)
            {
                Invoke(new PostUserCredentialsDelegate(PostUserCredentials), clientNumber, message);
                return;
            }

            try
            {
                var IncomingData = (PacketData)PacketFunctions.ByteArrayToStructure(message, typeof(PacketData));

                lock (_svr.WorkerSockets)
                {
                    var computerName =
                        new string(IncomingData.szStringDataA).TrimEnd('\0');                 //Station/Computer's name
                    var versionStr  = new string(IncomingData.szStringDataB).TrimEnd('\0');   //app version
                    var clientsName = new string(IncomingData.szStringData150).TrimEnd('\0'); //Client's Name

                    listView1.Items[clientNumber.ToString()].SubItems[1].Text = computerName;
                    listView1.Items[clientNumber.ToString()].SubItems[2].Text = versionStr;
                    listView1.Items[clientNumber.ToString()].SubItems[4].Text = clientsName;

                    if (_svr.WorkerSockets.ContainsKey(clientNumber))
                    {
                        _svr.WorkerSockets[clientNumber].SzStationName = computerName;

                        _svr.WorkerSockets[clientNumber].SzClientName = clientsName;

                        OnCommunications(
                            $"{GeneralFunctions.GetDateTimeFormatted} Registered Connection ({clientNumber}) for '{clientsName}' on PC: {computerName}",
                            Ink.ClrGreen);
                    }
                } //end lock
            }
            catch (Exception ex)
            {
                OnCommunications($"EXCEPTION: PostUserCredentials on client {clientNumber}, exception: {ex.Message}",
                                 Ink.ClrRed);
            }
        }
Пример #21
0
        private void SendMessageOfClientDisconnect(int clientId)
        {
            try
            {
                var xdata = new PacketData
                {
                    Packet_Type = (ushort)PacketTypes.ClientDisconnecting,
                    Data_Type   = 0,
                    Packet_Size = (ushort)Marshal.SizeOf(typeof(PacketData)),
                    maskTo      = 0,
                    idTo        = 0,
                    idFrom      = (uint)clientId
                };

                var byData = PacketFunctions.StructureToByteArray(xdata);
                _svr.SendMessage(byData);
            }
            catch
            {
                // ignored
            }
        }
Пример #22
0
        private void ReplyToHostPing(byte[] message)
        {
            try
            {
                PacketData IncomingData = new PacketData();
                IncomingData = (PacketData)PacketFunctions.ByteArrayToStructure(message, typeof(PacketData));

                /****************************************************************************************/
                //calculate how long that ping took to get here
                TimeSpan ts = (new DateTime(IncomingData.DataLong1)) - (new DateTime(_serverTime));
                Console.WriteLine(
                    $"{GeneralFunctions.GetDateTimeFormatted}: {string.Format("Ping From Server to client: {0:0.##}ms", ts.TotalMilliseconds)}");
                /****************************************************************************************/

                _serverTime = IncomingData.DataLong1; // Server computer's current time!

                PacketData xdata = new PacketData();

                xdata.Packet_Type = (ushort)PacketTypes.PingResponse;
                xdata.Data_Type   = 0;
                xdata.Packet_Size = 16;
                xdata.maskTo      = 0;
                xdata.idTo        = 0;
                xdata.idFrom      = 0;

                xdata.DataLong1 = IncomingData.DataLong1;

                byte[] byData = PacketFunctions.StructureToByteArray(xdata);

                SendMessageToServer(byData);

                CheckThisComputersTimeAgainstServerTime();
            }
            catch (Exception ex)
            {
                string exceptionMessage = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message;
                Console.WriteLine($"EXCEPTION IN: ReplyToHostPing - {exceptionMessage}");
            }
        }
Пример #23
0
        private void TellServerImDisconnecting()
        {
            try
            {
                PacketData xdata = new PacketData();

                xdata.Packet_Type = (ushort)PacketTypes.Close;
                xdata.Data_Type   = 0;
                xdata.Packet_Size = 16;
                xdata.maskTo      = 0;
                xdata.idTo        = 0;
                xdata.idFrom      = 0;

                byte[] byData = PacketFunctions.StructureToByteArray(xdata);

                SendMessageToServer(byData);
            }
            catch (Exception ex)
            {
                string exceptionMessage = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message;
                Console.WriteLine($"EXCEPTION IN: TellServerImDisconnecting - {exceptionMessage}");
            }
        }
Пример #24
0
        public void ReplyToHostCredentialRequest(byte[] message)
        {
            if (_client == null)
            {
                return;
            }

            Console.WriteLine($@"ReplyToHostCredentialRequest ThreadID = {Thread.CurrentThread.ManagedThreadId}");
            var loc = 0;

            try
            {
                //We will assume to tell the host this is just an update of the
                //credentials we first sent during the application start. This
                //will be true if the 'message' argument is null, otherwise we
                //will change the packet type below to the 'TYPE_MyCredentials'.
                var paketType = (ushort)PacketTypes.CredentialsUpdate;

                if (message != null)
                {
                    var myOldServerID = 0;
                    //The host server has past my ID.
                    var incomingData = (PacketData)PacketFunctions.ByteArrayToStructure(message, typeof(PacketData));
                    loc = 10;
                    if (_myHostServerId > 0)
                    {
                        myOldServerID = _myHostServerId;
                    }
                    loc             = 20;
                    _myHostServerId = (int)incomingData.idTo;  //Hang onto this value
                    loc             = 25;

                    Console.WriteLine($@"My Host Server ID is {_myHostServerId}");

                    var myAddressAsSeenByTheHost =
                        new string(incomingData.szStringDataA).TrimEnd('\0'); //My computer address
                    SetSomeLabelInfoFromThread(
                        $"My Address As Seen By The Server: {myAddressAsSeenByTheHost}, and my ID given by the server is: {_myHostServerId}");

                    _serverTime = incomingData.DataLong1;

                    paketType = (ushort)PacketTypes.MyCredentials;
                }

                var xdata = new PacketData
                {
                    Packet_Type = paketType,
                    Data_Type   = 0,
                    Packet_Size = (ushort)Marshal.SizeOf(typeof(PacketData)),
                    maskTo      = 0,
                    idTo        = 0,
                    idFrom      = 0
                };


                //Station Name
                var p = Environment.MachineName;
                if (p.Length > (xdata.szStringDataA.Length - 1))
                {
                    p.CopyTo(0, xdata.szStringDataA, 0, (xdata.szStringDataA.Length - 1));
                }
                else
                {
                    p.CopyTo(0, xdata.szStringDataA, 0, p.Length);
                }
                xdata.szStringDataA[(xdata.szStringDataA.Length - 1)] = '\0'; //cap it off just incase

                //App and DLL Version

                var versionNumber = Assembly.GetEntryAssembly().GetName().Version.Major + "." +
                                    Assembly.GetEntryAssembly().GetName().Version.Minor + "." +
                                    Assembly.GetEntryAssembly().GetName().Version.Build;

                loc = 30;

                versionNumber.CopyTo(0, xdata.szStringDataB, 0, versionNumber.Length);
                loc = 40;
                //Station Name
                var l = textBoxClientName.Text;
                if (l.Length > (xdata.szStringData150.Length - 1))
                {
                    l.CopyTo(0, xdata.szStringData150, 0, (xdata.szStringData150.Length - 1));
                }
                else
                {
                    l.CopyTo(0, xdata.szStringData150, 0, l.Length);
                }
                xdata.szStringData150[(xdata.szStringData150.Length - 1)] = '\0'; //cap it off just incase

                loc = 50;

                //Application type
                xdata.nAppLevel = (ushort)AppLevel.None;

                var byData = PacketFunctions.StructureToByteArray(xdata);
                loc = 60;
                SendMessageToServer(byData);
                loc = 70;
            }
            catch (Exception ex)
            {
                var exceptionMessage = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message;
                Console.WriteLine(
                    $@"EXCEPTION at location {loc}, IN: ReplyToHostCredentialRequest - {exceptionMessage}");
            }
        }
Пример #25
0
        private void buttonSendDataToServer_Click(object sender, EventArgs e)
        {
            PacketData xdata = new PacketData();

            /****************************************************************/
            //prepair the start packet
            xdata.Packet_Type = (ushort)PacketTypes.Message;
            xdata.Data_Type   = (ushort)PacketTypesSubMessage.Start;
            xdata.Packet_Size = 16;
            xdata.maskTo      = 0;
            xdata.idTo        = 0;
            xdata.idFrom      = 0;

            //Before we send the text, lets stuff those Number values in the first data packet!
            int num1 = 0;

            int.TryParse(textBoxNum1.Text, out num1);
            xdata.Data16 = num1;
            int num2 = 0;

            int.TryParse(textBoxNum2.Text, out num2);
            xdata.Data17 = num2;

            int pos       = 0;
            int chunkSize = xdata.szStringDataA.Length; //300 bytes

            if (textBoxText.Text.Length <= xdata.szStringDataA.Length)
            {
                textBoxText.Text.CopyTo(0, xdata.szStringDataA, 0, textBoxText.Text.Length);
                chunkSize = textBoxText.Text.Length;
            }
            else
            {
                textBoxText.Text.CopyTo(0, xdata.szStringDataA, 0, xdata.szStringDataA.Length);
            }

            xdata.Data1 = (uint)chunkSize;

            byte[] byData = PacketFunctions.StructureToByteArray(xdata);

            SendMessageToServer(byData);

            /**************************************************/
            //Send the message body(if there is any)
            xdata.Data_Type = (ushort)PacketTypesSubMessage.Guts;
            pos             = chunkSize; //set position
            while (true)
            {
                int PosFromEnd = textBoxText.Text.Length - pos;

                if (PosFromEnd <= 0)
                {
                    break;
                }

                Array.Clear(xdata.szStringDataA, 0,
                            xdata.szStringDataA.Length); //Clear this field before putting more data in it

                if (PosFromEnd < xdata.szStringDataA.Length)
                {
                    chunkSize = textBoxText.Text.Length - pos;
                }
                else
                {
                    chunkSize = xdata.szStringDataA.Length;
                }

                textBoxText.Text.CopyTo(pos, xdata.szStringDataA, 0, chunkSize);
                xdata.Data1 = (uint)chunkSize;
                pos        += chunkSize; //set new position

                byData = PacketFunctions.StructureToByteArray(xdata);
                SendMessageToServer(byData);
            }

            /**************************************************/
            //Send an EndMessage
            xdata.Data_Type = (ushort)PacketTypesSubMessage.End;
            xdata.Data1     = (uint)pos; //send the total which should be the 'pos' value
            byData          = PacketFunctions.StructureToByteArray(xdata);
            SendMessageToServer(byData);
        }