Exemple #1
0
        void AddPlayersNamesToPlayersListBox()
        {
            NetworkStream clientStream = this._tcpClient.GetStream();
            int           bytesRead = 0, index = 0, int_room_id = 0, temp_length = 0;
            int           number_of_players = 0, player_length_name = 0, temp = 4;

            byte[] bufferIn = new byte[913];
            string message = "", room_name = "", str_room_id = "";

            while (true)
            {
                index = this.rooms_names_listBox.SelectedIndex;
                if (index != -1 && index != this._save_last_index)
                {
                    this.problem_with_joining_label.Hide();
                    this.participants_in_room_listBox.Items.Clear();
                    this._save_last_index = index;
                    room_name             = this.rooms_names_listBox.SelectedItem.ToString();
                    int_room_id           = this._ids_of_rooms[index];
                    temp_length           = 4 - int_room_id;
                    for (int i = 0; i < temp_length; i++)
                    {
                        str_room_id += "0";
                    }
                    str_room_id += int_room_id.ToString();
                    try
                    {
                        byte[] buffer = new ASCIIEncoding().GetBytes("207" + str_room_id);
                        clientStream.Write(buffer, 0, buffer.Length);
                        clientStream.Flush();
                        bytesRead = clientStream.Read(bufferIn, 0, 913);
                        if (bytesRead == 0)
                        {
                            //the client has disconnected from the server
                            this._tcpClient.Close();
                        }
                        message = new ASCIIEncoding().GetString(bufferIn);
                    }
                    catch { }
                    if (message.Length >= 4)
                    {
                        if (message.Substring(0, 3).Equals("108"))
                        {
                            number_of_players = message[3] - 48;
                            for (int i = 0; i < number_of_players; i++)
                            {
                                player_length_name = int.Parse(message.Substring(temp, 2));
                                temp += 2;
                                this.participants_in_room_listBox.Items.Add(message.Substring(temp, player_length_name));
                                temp += player_length_name;
                            }
                        }
                        this.participants_in_room_listBox.Show();
                        str_room_id = "";
                        temp        = 4;
                    }
                }
            }
        }
Exemple #2
0
        void SendTheAnswer()
        {
            byte[] bufferIn    = new byte[5013];
            int    bytesRead   = 0;
            string message     = "";
            char   checkAnswer = ' ';

            this.answer1_btn.Enabled = false;
            this.answer2_btn.Enabled = false;
            this.answer3_btn.Enabled = false;
            this.answer4_btn.Enabled = false;
            try
            {
                byte[] buffer = new ASCIIEncoding().GetBytes("219" + this._number_answered.ToString() + this.AnswerTime());
                this._clientStream.Write(buffer, 0, buffer.Length);
                this._clientStream.Flush();
                bytesRead = this._clientStream.Read(bufferIn, 0, 4);
                if (bytesRead == 0)
                {
                    //the client has disconnected from the server
                    this._tcpClient.Close();
                }
                message = new ASCIIEncoding().GetString(bufferIn);
            }
            catch { }

            if (message.Length >= 3)
            {
                if (message.Substring(0, 3).Equals("120"))
                {
                    checkAnswer = message[3];
                    bytesRead   = this._clientStream.Read(bufferIn, 0, 5013);
                    if (bytesRead == 0)
                    {
                        //the client has disconnected from the server
                        this._tcpClient.Close();
                    }
                    message = new ASCIIEncoding().GetString(bufferIn);
                    if (message.Length >= 3)
                    {
                        if (message.Substring(0, 3).Equals("118"))
                        {
                            Thread load_question = new Thread(() => LoadQuestion(checkAnswer, message));
                            load_question.Start();
                        }

                        else if (message.Substring(0, 3).Equals("121"))
                        {
                            this._timer.Stop();
                            PaintAnswer(checkAnswer);
                            Scores scores = new Scores(message);
                            scores.ShowDialog();
                            this.Close();
                        }
                    }
                }
            }
        }
        public MyStatus_BestScores(TcpClient tcpClient, bool isMyStatus)
        {
            InitializeComponent();
            this._tcpClient  = tcpClient;
            this._isMyStatus = isMyStatus;
            Thread t = new Thread(new ThreadStart(BeautyTriviaLabel));

            t.Start();
            NetworkStream clientStream = tcpClient.GetStream();

            byte[] bufferIn  = new byte[324];
            int    bytesRead = 0;
            string message   = "";
            string send      = "";

            if (this._isMyStatus)
            {
                send = "225";
            }

            else
            {
                this.average_time_for_answer.Hide();
                send = "223";
                this.number_of_games_label.Text         = "";
                this.number_of_right_answers_label.Text = "";
                this.number_of_wrong_answers_label.Text = "";
            }
            try
            {
                byte[] buffer = new ASCIIEncoding().GetBytes(send);
                clientStream.Write(buffer, 0, buffer.Length);
                clientStream.Flush();
                bytesRead = clientStream.Read(bufferIn, 0, bufferIn.Length);
                if (bytesRead == 0)
                {
                    //the client has disconnected from the server
                    this._tcpClient.Close();
                }
                message = new ASCIIEncoding().GetString(bufferIn);
            }
            catch { }
            if (message.Length >= 3)
            {
                if (message.Substring(0, 3).Equals("126"))
                {
                    this.GetMyStatus(message);
                }

                else if (message.Substring(0, 3).Equals("124"))
                {
                    this.GetBestScores(message);
                }
            }
        }
Exemple #4
0
        public static string RecvMsg(NetworkStream sock)
        {//recieve the messages for all the program
            bool endFound = false;

            //recive signin answer
            byte[] bufferIn  = new byte[4096];
            int    bytesRead = sock.Read(bufferIn, 0, 4096);
            string input     = new ASCIIEncoding().GetString(bufferIn);

            for (int i = 0; i < input.Length && !endFound; i++)
            {
                if (input[i] == '\0')
                {
                    endFound = true;
                    input    = input.Substring(0, i);
                }
            }

            if (key != 0)
            {
                input = Decrypto(input);
            }

            var log = Application.OpenForms.OfType <LogForm>().Single();

            log.Invoke((MethodInvoker) delegate { log.SetLog(log.GetLog() + "Recived: " + input + "\n\n"); });

            return(input);
        }
Exemple #5
0
 public override bool PortDataRecv(CMessage sSend, CRecvBuff cRecv)
 {
     try
     {
         base.PortDataRecv(sSend, cRecv);
         string sRecv = new ASCIIEncoding().GetString(cRecv.bRecvBuff, 0, cRecv.iRecvLen);
         int    iMark = sRecv.IndexOf(Address);
         if (iMark >= 0)
         {
             int    iFF    = sRecv.IndexOf('\r', iMark);
             string sValue = sRecv.Substring(iMark + 6, iFF - iMark - 6);
             lock (this)
             {
                 cRecv.DelBuff(iFF + 3);
             }
             CommStateE         = ECommSatate.Normal;
             present_MsgFailRep = 0;
             present_DevFailNum = 0;
             present_DevFailCyc = 0;
             return(GetVarValue(sSend, sValue));
         }
         return(false);
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
        public Message(byte[] package)
        {
            string temp = new ASCIIEncoding().GetString(package);

            totalmessage = temp;
            temp         = temp.Trim();
            if (temp.StartsWith("<") && temp.EndsWith(">"))
            {
                temp = temp.Substring(1, temp.Length - 2);
                string[] strmsg = temp.Split(',');
                this.stationId = strmsg[0];
                this.MsgId     = Convert.ToInt32(strmsg[1]);
                this.MsgType   = (MsgType)strmsg[2][0];
                this.Info      = strmsg[3];
                if (strmsg.Length > 4)
                {
                    this.DutID = strmsg[4];
                }
                string[] strmsg2 = this.Info.Split(':');
                if (strmsg2[0] == "E")
                {
                    this.Info      = "E";
                    this.ErrorInfo = strmsg2[1];
                }
            }
        }
Exemple #7
0
        public string getSKID(Org.BouncyCastle.X509.X509Certificate cert)
        {
            DerObjectIdentifier identifier = new DerObjectIdentifier("2.5.29.14");

            byte[] skid       = Hex.Encode(cert.GetExtensionValue(identifier).GetOctets());
            string skidstring = new ASCIIEncoding().GetString(skid);

            return(skidstring.Substring(4));
        }
Exemple #8
0
        public static string GetAsciiString(byte[] msg, ref int pos, int len)
        {
            string value = new ASCIIEncoding().GetString(msg, pos, len);

            pos += len;
            if (len > 0 && value[len - 1] == 0x0000)
            {
                value = value.Substring(0, len - 1);
            }
            return(value);
        }
Exemple #9
0
        public static string GetAsciiStringLen32(byte[] msg, ref int pos)
        {
            var    len   = (int)GetUInt32(msg, ref pos);
            string value = new ASCIIEncoding().GetString(msg, pos, len);

            pos += len;
            if (len > 0 && value[len - 1] == 0x0000)
            {
                value = value.Substring(0, len - 1);
            }
            return(value);
        }
Exemple #10
0
        void LoadRoomsNames()
        {
            NetworkStream clientStream = this._tcpClient.GetStream();
            int           bytesRead = 0, number_of_rooms = 0, temp = 7, room_id = 0, room_length = 0;

            byte[] bufferIn = new byte[1049902];
            string message = "", room_name = "";

            try
            {
                byte[] buffer = new ASCIIEncoding().GetBytes("205");
                clientStream.Write(buffer, 0, buffer.Length);
                clientStream.Flush();
                bytesRead = clientStream.Read(bufferIn, 0, 1049902);
                if (bytesRead == 0)
                {
                    //the client has disconnected from the server
                    this._tcpClient.Close();
                }
                message = new ASCIIEncoding().GetString(bufferIn);
            }
            catch { }
            if (message.Length >= 7)
            {
                number_of_rooms = int.Parse(message.Substring(3, 4));
                for (int i = 0; i < number_of_rooms; i++)
                {
                    room_id     = int.Parse(message.Substring(temp, 4));
                    temp       += 4;
                    room_length = int.Parse(message.Substring(temp, 2));
                    temp       += 2;
                    room_name   = message.Substring(temp, room_length);
                    temp       += room_length;
                    this._ids_of_rooms.Add(room_id);
                    this.rooms_names_listBox.Items.Add(room_name);
                }
            }
        }
Exemple #11
0
 public static string ToAsciiString(this byte[] array)
 {
     lock (ToStringExtensions.lockByteToString)
     {
         if (array == null)
         {
             return(string.Empty);
         }
         string str    = new ASCIIEncoding().GetString(array, 0, array.Length);
         int    length = str.IndexOf(char.MinValue);
         if (length >= 0)
         {
             str = str.Substring(0, length);
         }
         return(str.TrimEnd(' '));
     }
 }
Exemple #12
0
        //PLC message convert
        public MainPLCMessage(byte[] data)
        {
            string temp = new ASCIIEncoding().GetString(data);

            temp = temp.Trim();
            string messageState = "";
            string errorCode    = "";

            //useful message no less than message head
            if (temp.Length >= msgHeadLength)
            {
                this.MsgType        = (PLCMsgType)temp[0];              //get messagetype
                this.MsgHead        = temp.Substring(0, msgHeadLength); //get message head
                this.InvalidMessage = false;                            //vaild message
                // messageState = temp.Substring(4, errCodeLength);
                switch (this.MsgType)
                {
                case PLCMsgType.Feedback:
                    this.Info = "";
                    if (this.MsgHead == MoveDUTToStationACK)
                    {
                        this.StationId = Convert.ToInt16(temp.Substring(4, _StationIdLength));
                        messageState   = temp.Substring(6, errCodeLength);
                        if (messageState == "00")
                        {
                            this.isok = true;
                            this.Info = " DUT placed to Station " + StationId;
                        }
                        else if (messageState == "01")
                        {
                            this.isok = false;
                            //error code handle add to this.info
                        }
                    }
                    else if (this.MsgHead == MoveDUTFromStationACK)
                    {
                        this.StationId = Convert.ToInt16(temp.Substring(4, _StationIdLength));
                        messageState   = temp.Substring(6, errCodeLength);
                        if (messageState == "00")
                        {
                            this.isok = true;
                            this.Info = "DUT move away from Station " + StationId;
                        }
                        else if (messageState == "01")
                        {
                            this.isok = false;
                            //error code handle add to this.info
                        }
                    }
                    else if (this.MsgHead == queryPLCStateACK)
                    {
                        messageState = temp.Substring(4, errCodeLength);
                        if (messageState == "00")
                        {
                            this.isok      = true;
                            this.PLCIsBusy = false;
                        }
                        else if (messageState == "01")
                        {
                            this.isok      = true;
                            this.PLCIsBusy = true;
                        }
                        else if (messageState == "02")
                        {
                            this.isok = false;
                            //error code handle add to this info
                        }
                    }

                    break;

                case PLCMsgType.Heartbead:
                    this.Info = "Heartbeat";
                    break;

                case PLCMsgType.ReportMsg:
                    if (this.MsgHead == DUTIdToServer)
                    {
                        this.isok = true;
                        this.Info = temp.Substring(4, dutIDLength);
                    }
                    break;

                case PLCMsgType.Ack:
                    this.Info = "Ack";
                    break;

                default:
                    break;
                }
            }
            else
            {
                this.InvalidMessage = true;
                this.Info           = temp;
            }
        }
Exemple #13
0
        private void Com_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] ReDatas = new byte[comDevice.BytesToRead];
            comDevice.Read(ReDatas, 0, ReDatas.Length);

            String sdata = new ASCIIEncoding().GetString(ReDatas);

            try
            {
                if (sdata.StartsWith("t"))
                {
                    if (sdata.Length != 21)
                    {
                        //byte[] strBuffer = System.Text.Encoding.ASCII.GetBytes(yourASCIIString);
                        string str = "wrong data length, please be check!";
                        MessageBox.Show(str);
                        comDevice.Write(str);
                    }
                    if (int.Parse(sdata.Substring(4, 1)) > 8)
                    {
                        string str = "wrong data bit , please be check!";
                        MessageBox.Show(str);
                        comDevice.Write(str);
                    }
                    if (!cal.InOrNot(sdata.Substring(1, 3)))
                    {
                        string str = "no this data id, please be check!";
                        MessageBox.Show(str);
                        comDevice.Write(str);
                    }
                }
                else if (sdata.StartsWith("T"))
                {
                    if (sdata.Length != 26)
                    {
                        string str = "wrong data length, please be check!";
                        MessageBox.Show(str);
                        comDevice.Write(str);
                    }
                    if (int.Parse(sdata.Substring(9, 1)) > 8)
                    {
                        string str = "wrong data bit , please be check!";
                        MessageBox.Show(str);
                        comDevice.Write(str);
                    }
                    if (!cal.InOrNot(sdata.Substring(1, 8)))
                    {
                        string str = "no this data id, please be check!";
                        MessageBox.Show(str);
                        comDevice.Write(str);
                    }
                }
                else
                {
                    string str = "wrong data, please be check!";
                    MessageBox.Show(str);
                    comDevice.Write(str);
                }
            }
            catch
            {
                return;
            }
            // MessageBox.Show(sdata);
            if (sdata == null || sdata.Trim() == "")
            {
                String current_data = Message_DataBase.get_current_data();
                if (current_data != null)
                {
                    sdata = current_data;
                }
                return;
            }
            Message_DataBase.set_current_data(sdata);


            dic = cal.Decode(sdata);

            //dic长度为0
            //MessageBox.Show("dic的长度为:" + dic.Count().ToString());
            Font boldFont = new Font(treeGridView1.DefaultCellStyle.Font, FontStyle.Bold);


            if (this.IsHandleCreated)
            {
                this.BeginInvoke(new MethodInvoker(delegate
                {
                    if (!message.Contains(cal.messagename))
                    {
                        message.Add(cal.messagename);
                        TreeGridNode node_temp = treeGridView1.Nodes.Add(null, cal.messagename, " ");

                        foreach (KeyValuePair <string, string> kv in dic)
                        {
                            signalname.Add(kv.Key);
                            node.Add(node_temp);
                            node[i]                       = node_temp.Nodes.Add(null, kv.Key, kv.Value);
                            node[i].ImageIndex            = 0;
                            node[i].DefaultCellStyle.Font = boldFont;
                            i++;
                        }
                    }
                    else
                    {
                        foreach (KeyValuePair <string, string> kv in dic)
                        {
                            for (int j = 0; j < signalname.Count(); j++)
                            {
                                if (kv.Key == signalname[j])
                                {
                                    node[j]                       = node[j].Nodes.Add(null, " ", kv.Value);
                                    node[j].ImageIndex            = 1;
                                    node[j].DefaultCellStyle.Font = boldFont;
                                }
                            }
                        }
                    }

                    /*   if (!signalname.Contains(kv.Key))
                     * {
                     *     TreeGridNode node_temp = treeGridView1.Nodes.Add(null, cal.messagename, " ");
                     *     signalname.Add(kv.Key);
                     *
                     *     //node.Add(new TreeGridNode());
                     *     TreeGridNode node_temp = treeGridView1.Nodes.Add(null, kv.Key, kv.Value);
                     *     node.Add(node_temp);
                     *     // node[i]=treeGridView1.Nodes.Add(null, kv.Key, kv.Value);
                     *     node[i].ImageIndex = 0;
                     *     node[i].DefaultCellStyle.Font = boldFont;
                     *     i++;
                     * }
                     * else
                     * {*/
                }));
            }


            // MessageBox.Show("kv.Key");

            /*
             * TreeGridNode node2 = treeGridView1.Nodes.Add(null, "kv.Key"," kv.Value");
             * node2.ImageIndex = 0;
             * node2.DefaultCellStyle.Font = boldFont;
             * node2 = node2.Nodes.Add(null, "Re: Using DataView filter when binding to DataGridView", "tab");
             * node2.ImageIndex = 1;*/


            foreach (KeyValuePair <string, string> kv in dic)
            {
                // string temp = "\r\n this is here!";
                string temp = kv.Key + "\'s physical value is :" + kv.Value;

                //向数据库中插入数据
                DbManager.Ins.ConnStr = "server = localhost; user id = root; password = root; database = cantool";
                string sql = @"INSERT into can_message(can_message.signal_name, can_message.signal_value,can_message.time) VALUES (?signal_name, ?signal_value, ?time)";
                List <MySqlParameter> Paramter = new List <MySqlParameter>();
                Paramter.Add(new MySqlParameter("?signal_name", kv.Key));
                Paramter.Add(new MySqlParameter("?signal_value", kv.Value));
                Paramter.Add(new MySqlParameter("?time", DateTime.Now.ToLocalTime().ToString()));
                int    insert    = DbManager.Ins.ExecuteNonquery(sql, Paramter.ToArray());
                byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(temp);
                // this.AddData(byteArray);
            }
        }
Exemple #14
0
        public long GetUID(ref byte[] UID)
        {
            long _result      = 0;
            bool cardInserted = false;


            IntPtr _CardContext   = IntPtr.Zero;
            IntPtr ActiveProtocol = IntPtr.Zero;

            // Establish Reader context:
            if (this._ReaderContext == IntPtr.Zero)
            {
                _result = SCardEstablishContext(2, IntPtr.Zero, IntPtr.Zero, out this._ReaderContext);

                #region Get List of Available Readers

                uint pcchReaders = 0;
                int  nullindex   = -1;
                char nullchar    = (char)0;

                // First call with 3rd parameter set to null gets readers buffer length.
                _result = SCardListReaders(this._ReaderContext, null, null, ref pcchReaders);

                byte[] mszReaders = new byte[pcchReaders];

                // Fill readers buffer with second call.
                _result = SCardListReaders(this._ReaderContext, null, mszReaders, ref pcchReaders);

                // Populate List with readers.
                string currbuff = new ASCIIEncoding().GetString(mszReaders);
                int    len      = (int)pcchReaders;

                if (len > 0)
                {
                    while (currbuff[0] != nullchar)
                    {
                        nullindex = currbuff.IndexOf(nullchar);                           // Get null end character.
                        string reader = currbuff.Substring(0, nullindex);
                        this._AvailableReaders.Add(reader);
                        len      = len - (reader.Length + 1);
                        currbuff = currbuff.Substring(nullindex + 1, len);
                    }
                }

                #endregion

                // Select the first reader:
                this._ReaderName = this._AvailableReaders[0];
            }

            try
            {
                //Check if there is a Card in the reader:

                //dwShareMode: SCARD_SHARE_SHARED = 0x00000002 - This application will allow others to share the reader
                //dwPreferredProtocols: SCARD_PROTOCOL_T0 - Use the T=0 protocol (value = 0x00000001)

                if (this._ReaderContext != IntPtr.Zero)
                {
                    _result = SCardConnect(this._ReaderContext, this._ReaderName, 0x00000002, 0x00000001, ref _CardContext, ref ActiveProtocol);
                    if (_result == 0)
                    {
                        cardInserted = true;

                        SCARD_IO_REQUEST request = new SCARD_IO_REQUEST()
                        {
                            dwProtocol  = (uint)ActiveProtocol,
                            cbPciLength = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(SCARD_IO_REQUEST))
                        };

                        byte[] sendBytes = new byte[] { 0xFF, 0xCA, 0x00, 0x00, 0x00 };                         //<- get UID command for iClass cards
                        byte[] ret_Bytes = new byte[33];
                        uint   sendLen   = (uint)sendBytes.Length;
                        uint   ret_Len   = (uint)ret_Bytes.Length;

                        _result = SCardTransmit(_CardContext, ref request, ref sendBytes[0], sendLen, ref request, ret_Bytes, ref ret_Len);
                        if (_result == 0)
                        {
                            UID = ret_Bytes.Take(4).ToArray();                             //only take the first 8, the last 2 bytes are not part of the UID of the card
                            string dataOut = byteToHexa(UID, UID.Length, true).Trim();     //Devolver la respuesta en Hexadecimal
                        }
                    }
                }
            }
            finally
            {
                SCardDisconnect(_CardContext, 0);
                SCardReleaseContext(this._ReaderContext);
            }
            return(_result);
        }
Exemple #15
0
        private void join_btn_Click(object sender, EventArgs e)
        {
            NetworkStream clientStream = this._tcpClient.GetStream();
            int           bytesRead    = 0;

            byte[] bufferIn = new byte[8];
            int    index = this.rooms_names_listBox.SelectedIndex, int_room_id = 0, temp_length = 0;
            string room_name = "", message = "", str_room_id = "", number_of_questions = "", time_for_question = "";

            if (index != -1)
            {
                room_name   = this.rooms_names_listBox.SelectedItem.ToString();
                int_room_id = this._ids_of_rooms[index];
                temp_length = 4 - int_room_id.ToString().Length;
                for (int i = 0; i < temp_length; i++)
                {
                    str_room_id += "0";
                }
                str_room_id += int_room_id.ToString();
                try
                {
                    byte[] buffer = new ASCIIEncoding().GetBytes("209" + str_room_id);
                    clientStream.Write(buffer, 0, buffer.Length);
                    clientStream.Flush();
                    bytesRead = clientStream.Read(bufferIn, 0, 8);
                    if (bytesRead == 0)
                    {
                        //the client has disconnected from the server
                        this._tcpClient.Close();
                    }
                    message = new ASCIIEncoding().GetString(bufferIn);
                }
                catch { }
                if (message.Substring(0, 4).Equals("1100"))
                {
                    number_of_questions = int.Parse(message.Substring(4, 2)).ToString();
                    time_for_question   = int.Parse(message.Substring(6, 2)).ToString();
                    try
                    {
                        byte[] buffer = new ASCIIEncoding().GetBytes("207" + str_room_id);
                        clientStream.Write(buffer, 0, buffer.Length);
                        clientStream.Flush();
                    }
                    catch { }
                    this._write_into_players_listBox.Abort();
                    this.Hide();
                    BeforeBeginGame bbg = new BeforeBeginGame(this._tcpClient, false, "", room_name, str_room_id, "", number_of_questions, time_for_question);
                    bbg.ShowDialog();
                    this.Close();
                }

                else
                {
                    if (message.Substring(0, 4).Equals("1101"))
                    {
                        this.problem_with_joining_label.Text = "room is full";
                    }

                    else
                    {
                        this.problem_with_joining_label.Text = "game has started/room has closed etc...";
                    }
                    this.problem_with_joining_label.Show();
                }
            }

            else
            {
                if (this.rooms_names_listBox.Items.Count > 0)
                {
                    this.problem_with_joining_label.Text = "pick a room";
                    this.problem_with_joining_label.Show();
                }
            }
        }