Serialize() public abstract method

public abstract Serialize ( MemoryStream stream ) : void
stream MemoryStream
return void
Esempio n. 1
0
        public void TestSerialize()
        {
            byte Command = 0xE1;

            byte[] Payload   = new byte[] { 0xA1, 0xA2, 0x33, 0x44 };
            byte   Checksum1 = 0x05;
            byte   Checksum2 = 0x30;

            byte[] Message = new byte[] { 0x0E, 0xE0, 0x0A, 0XE1, 0xA1, 0xA2, 0x33, 0x44, 0x05, 0x30 };
            byte[] test    = p.Serialize(Command, Payload, Checksum1, Checksum2);

            Assert.AreEqual(4, Payload.Length);
            Assert.AreEqual(Message[0], test[0]);
            Assert.AreEqual(Message[1], test[1]);
            Assert.AreEqual(Message[2], test.Length);
            Assert.AreEqual(Message[2], test[2]);
            Assert.AreEqual(Message[3], test[3]);
            Assert.AreEqual(Message[4], test[4]);
            Assert.AreEqual(Message[5], test[5]);
            Assert.AreEqual(Message[6], test[6]);
            Assert.AreEqual(Message[7], test[7]);
            Assert.AreEqual(Message[8], test[8]);
            Assert.AreEqual(Message[9], test[9]);

            for (int i = 0; i < test.Length; i++)
            {
                Assert.AreEqual(Message[i], test[i]);
            }
        }
Esempio n. 2
0
        public void TestSerializeCorrectComplete()
        {
            //Test een normaal bericht om te versturen, zonder bijzonderheden
            byte Command = 0xE1;

            byte[] Payload    = new byte[] { 0xA1, 0xA2, 0x33, 0x44 };
            UInt16 Identifier = 0X1001;

            byte[] Message = new byte[] { 0x0E, 0xE0, 0x0C, 0XE1, 0X10, 0X01, 0xA1, 0xA2, 0x33, 0x44, 0x80, 0xA9 };
            byte[] test    = p.Serialize(Command, Identifier, Payload);

            Assert.AreEqual(4, Payload.Length);
            Assert.AreEqual(Message[0], test[0]);
            Assert.AreEqual(Message[1], test[1]);
            Assert.AreEqual(Message[2], test.Length);
            Assert.AreEqual(Message[2], test[2]);
            Assert.AreEqual(Message[3], test[3]);
            Assert.AreEqual(Message[4], test[4]);
            Assert.AreEqual(Message[5], test[5]);
            Assert.AreEqual(Message[6], test[6]);
            Assert.AreEqual(Message[7], test[7]);
            Assert.AreEqual(Message[8], test[8]);
            Assert.AreEqual(Message[9], test[9]);
            Assert.AreEqual(0X80, test[10]);
            Assert.AreEqual(0XA9, test[11]);
        }
        private void trvDir_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            before_expand_request request_data = new before_expand_request();

            request_data.Type = (int)PacketType.beforeExpand요청;

            e.Node.Nodes.Clear();
            request_data.dir_path = e.Node.FullPath;

            Packet.Serialize(request_data).CopyTo(this.sendBuffer, 0);
            this.Send();

            this.m_networkstream.Read(readBuffer, 0, 1024 * 4);

            before_expand_response temp_response = (before_expand_response)Packet.Desserialize(this.readBuffer);

            foreach (dir_info temp_dir in temp_response.dir_list)
            {
                TreeNode node = e.Node.Nodes.Add(temp_dir.file_name);
                if (temp_dir.is_dir)
                {
                    node.Nodes.Add("");
                }
            }
        }
        public void init_data()
        {
            init_data_request request_data = new init_data_request();

            request_data.Type = (int)PacketType.초기화데이터요청;

            Packet.Serialize(request_data).CopyTo(this.sendBuffer, 0);
            this.Send();

            this.m_networkstream.Read(readBuffer, 0, 1024 * 4);

            init_data_response temp_respnse = (init_data_response)Packet.Desserialize(this.readBuffer);

            TreeNode root;

            root            = trvDir.Nodes.Add(temp_respnse.rootName);
            root.ImageIndex = 1;

            if (trvDir.SelectedNode == null)
            {
                trvDir.SelectedNode = root;
            }
            root.SelectedImageIndex = root.ImageIndex;
            root.Nodes.Add("");
        }
Esempio n. 5
0
    public void OnNextQuestionPressed()
    {
        var msg = new Message();

        msg.action = Action.NextQuestion;
        SendMessage(Packet.Serialize(msg));
    }
Esempio n. 6
0
        public void SendTo()
        {
            FileStream   fs    = new FileStream(textBox4.Text, FileMode.Open, FileAccess.Read);
            BinaryReader read  = new BinaryReader(fs);
            FileInfo     fi    = new FileInfo(textBox4.Text);
            int          count = (int)(fi.Length / (1024 * 3)) + 1;

            NameSize ns = new NameSize();

            ns.name = fi.Name;

            ns.Type = (int)PacketType.이름과사이즈;
            Packet.Serialize(ns).CopyTo(this.sendBuffer, 0);
            this.Client_Send();

            progressBar1.Maximum = (int)fi.Length;

            for (int i = 0; i < count; i++)
            {
                DataSend ds = new DataSend();
                ds.data = read.ReadBytes(1024 * 3);
                ds.Type = (int)PacketType.일;

                progressBar1.Value += progressBar1.Maximum / count;

                Packet.Serialize(ds).CopyTo(this.sendBuffer, 0);
                this.Client_Send();
            }

            progressBar1.Value = 0;
        }
Esempio n. 7
0
        private void add_list_Click(object sender, EventArgs e) //Music List - 재생목록의 추가 버튼
        {
            if (!this.m_blsCientOn)                             //client연결 되어 있지 않다면
            {
                return;
            }

            if (downTxt.Text.CompareTo("") == 0)    //다운 경로 지정하지 않았다면
            {
                DialogResult dr = MessageBox.Show("파일을 다운받을 경로를 지정하지 않았습니다", "에러", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                int index;
                index = musicList.FocusedItem.Index;    //선택 된 아이템 인덱스
                string musicName = musicList.Items[index].Text;

                ClientRequest request = new ClientRequest();    //ClientRequest로 요청하는 음악 제목 서버로 보냄
                request.Type      = (int)PacketType.SendToServer;
                request.musicName = musicName;

                Packet.Serialize(request).CopyTo(sendBuffer, 0);
                this.Send();
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Encapsulates the audio data and sends it to the server using the message type that corresponds to your specified MimeType.
        /// </summary>
        /// <param name="AudioData">A byte array containing the payload for this packet.</param>
        /// <returns></returns>
        public byte[] SerializedAudioData(byte[] AudioData)
        {
            MessageFlag AudioFlag;

            switch (AudioMimeType)
            {
            case MimeType.Mp3:
                AudioFlag = MessageFlag.Mp3Data;
                break;

            case MimeType.Aacp:
                AudioFlag = MessageFlag.AacpData;
                break;

            case MimeType.Aac:
                AudioFlag = MessageFlag.AacLcData;
                break;

            case MimeType.Ogg:
                AudioFlag = MessageFlag.VorbisData;
                break;

            default:
                throw new MimeTypeException();
            }

            return(Packet.Serialize(AudioFlag, AudioData));
        }
        protected override byte[] Serialize(ClientEvent evt)
        {
            var stream = new MemoryStream();

            Packet.Serialize(evt, stream, new byte[16]);
            return(stream.ToArray());
        }
Esempio n. 10
0
File: Form1.cs Progetto: pr0gr4m/FM
        private void viewServer_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            string   path;
            TreeNode node;

            try
            {
                e.Node.Nodes.Clear();
                path = e.Node.FullPath;
                DirInfo dirInfo = new DirInfo(path);
                dirInfo.Type = (int)PacketType.ReqDirList;
                Packet.Serialize(dirInfo).CopyTo(this.sendBuf, 0);
                this.Send();

                Recv();
                DirList dirList = (DirList)Packet.Deserialize(this.recvBuf);

                foreach (string dir in dirList.dirList)
                {
                    node = e.Node.Nodes.Add(dir);
                    node.Nodes.Add("");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 11
0
        public Form2(string s1, string s2, string s3)
        {
            ip   = s1;
            port = Convert.ToInt32(s2);
            id   = s3;
            InitializeComponent();
            SetupVar();
            panel1.MouseWheel += new MouseEventHandler(mousewheel);
            this.m_client      = new TcpClient();
            try
            {
                this.m_client.Connect(ip, port);
            }
            catch
            {
                MessageBox.Show("접속 에러");
                return;
            }
            this.m_bConnect      = true;
            this.m_networkstream = this.m_client.GetStream();

            m_thread = new Thread(new ThreadStart(Receive));
            m_thread.Start();
            Text text = new Text();

            text.Type = (int)PacketType.문자열;
            text.mode = 2;
            text.id   = id;
            Packet.Serialize(text).CopyTo(this.sendBuffer, 0);
            this.Send();
        }
Esempio n. 12
0
        public void PacketFileInfo(ref Packet packet)
        {
            if (DEBUGGING)
            {
                Message("[+] PacketFileInfo");
            }
            File_Info fi = (File_Info)packet;

            DirectoryInfo di = new DirectoryInfo(fi.path);

            DirectoryInfo[] di_under = di.GetDirectories();
            FileInfo[]      fiArray  = di.GetFiles();

            ((File_Info)packet).fiArray = fiArray;
            ((File_Info)packet).diArray = di_under;
            try
            {
                Packet.Serialize(packet).CopyTo(sendBuffer, 0);
                //아하 sendBuffer가 너무 작아서 일어나는 문제구나..
                Send();
            }
            catch
            {
                MessageBox.Show("파일이 너무 많아서 info용량때메 오류가 나는 듯");
            }


            if (DEBUGGING)
            {
                Message("[-] PacketFileInfo");
            }
        }
Esempio n. 13
0
        private void person_num()
        {
            Team_Info m_Team_Info = new Team_Info();

            m_Team_Info.Type   = (int)PacketType.팀인원수;
            m_Team_Info.t_name = curID;
            int count = 0;

            Packet.Serialize(m_Team_Info).CopyTo(this.sendBuffer, 0);
            this.Send();

            //(정상인지 오류인지) 해당 팀 이름이 이미 사용중인지 아닌지 정보 받기
            this.Recv();
            Packet packet = (Packet)Packet.Deserialize(this.readBuffer);

            if ((int)packet.Type == (int)PacketType.팀인원수)
            {
                m_Team_Info = (Team_Info)Packet.Deserialize(this.readBuffer);
                count       = m_Team_Info.stCount;
                if (count < 4)
                {
                    MessageBox.Show("Team Match 불가 \n(팀 인원 수 최소 3명)");
                    pForm.sel_num = -1;
                    this.Close();
                }
            }

            comboBox1.Items.Clear();
            for (int i = count; i > 2; i--)
            {
                comboBox1.Items.Add(i + " 명");
            }
            comboBox1.SelectedIndex = 0;
        }
Esempio n. 14
0
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            PwClientSetting mChild = new PwClientSetting(this);

            if (mChild.ShowDialog() == DialogResult.OK)
            {
                MessageBox.Show("Completed Password Setting!", "Success",
                                MessageBoxButtons.OK, MessageBoxIcon.None); //성공 메시지 띄우기
            }

            //해당 팀 정보 불러오기
            this.m_Team_Info        = new Team_Info();
            this.m_Team_Info.Type   = (int)PacketType.로그인정보확인;
            this.m_Team_Info.t_name = team_name;

            Packet.Serialize(this.m_Team_Info).CopyTo(this.sendBuf, 0);
            this.m_networkstream = m_client.GetStream();
            this.Send();

            this.Recv();
            Packet pack = (Packet)Packet.Deserialize(this.readBuf);

            if ((int)pack.Type == (int)PacketType.로그인정보확인)
            {
                this.m_Team_Info = (Team_Info)Packet.Deserialize(this.readBuf);
                this.team_pw     = this.m_Team_Info.pw;
                this.st_count    = this.m_Team_Info.stCount;
            }
        }
Esempio n. 15
0
        private void upload()
        {
            try
            {
                //save received post data
                if (this.f_writer == null)
                {
                    f_writer = new StreamWriter("post.txt", true);
                }
                string str = string.Format(this.post.ID + "," + Convert.ToBase64String(this.post.picture) + "," + this.post.comment + "," + this.post.time);
                f_writer.WriteLine(str);
                f_writer.Flush();
                f_writer.Close();
                f_writer = null;

                this.success.success = true;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                //MessageBox.Show(Encoding.UTF8.GetString(this.post.picture));
                this.success.success = false;
            }

            //serialize and send to client
            Packet.Serialize(this.success).CopyTo(w_buffer, 0);
            send();
        }
        /// <summary>
        /// Write to the <see cref="NetworkStream"/>
        /// </summary>
        /// <param name="sendBuffer">The bytes we want to send</param>
        protected override void OnSending(Packet packetToSend)
        {
            // Serialize our packet into a byte[]
            byte[] sendBuffer = Packet.Serialize(packetToSend);

            m_networkStream.Write(sendBuffer, 0, sendBuffer.Length);
        }
Esempio n. 17
0
 private void brnDecryption_Click(object sender, EventArgs e)
 {
     try {
         if (Serial.IsOpen)
         {
             if (!String.IsNullOrWhiteSpace(txtMessageDecryption.Text) && !String.IsNullOrWhiteSpace(txtDecryptionKey.Text) && !string.IsNullOrWhiteSpace(cobDecryptionType.SelectedItem.ToString()))
             {
                 if (Ready)
                 {
                     Packet pak = new Packet(txtMessageDecryption.Text, txtDecryptionKey.Text, false, cobDecryptionType.SelectedItem.ToString(), "request");
                     pak.SetHashCode();
                     OutputBuffer.Add(pak);
                     Serial.Write(Packet.Serialize(pak, false) + "\n");
                     ConsoleWrite($"Data sent to port: '{Serial.PortName}', to be decrypted, the data sent is:\r\n {Packet.Serialize(pak, true)} ");
                 }
                 else
                 {
                     MessageBox.Show("The arduino isn't ready. please retry.");
                 }
             }
         }
         else
         {
             MessageBox.Show("The Client is not connected to a serial port", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
     catch (Exception) {
         MessageBox.Show("Select a value in the Combobox", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Esempio n. 18
0
        /// <summary>
        /// Concise way of flushing and then updating the distribution point's metadata
        /// </summary>
        /// <param name="MetadataInstance">A ShoutcastMetadata instance with the new data to send to the server, with all desired fields filled out.</param>
        public void PerformMetadataUpdate(ShoutcastMetadata MetadataInstance)
        {
            FlushCachedMetadata();

            var XmlNamespaces = new XmlSerializerNamespaces();

            XmlNamespaces.Add("", "");

            XmlSerializer Serializer = new XmlSerializer(typeof(ShoutcastMetadata));
            StringBuilder Sb         = new StringBuilder();

            int MetadataId    = 1;
            int MetadataSpan  = 1;
            int MetadataIndex = 1;

            byte[] XmlHead = new byte[] { 0x0, Convert.ToByte(MetadataId), 0x0, Convert.ToByte(MetadataSpan), 0x0, Convert.ToByte(MetadataIndex) };
            byte[] XmlBytes;

            using (StringWriter Writer = new StringWriter(Sb))
            {
                Serializer.Serialize(Writer, MetadataInstance, XmlNamespaces);
                XmlBytes = Encoding.UTF8.GetBytes(Writer.ToString().Replace("utf-16", "UTF-8"));
                Array.Resize <byte>(ref XmlBytes, XmlBytes.Length + 6);

                Buffer.BlockCopy(XmlBytes, 0, XmlBytes, 6, XmlBytes.Length - 6);
                Buffer.BlockCopy(XmlHead, 0, XmlBytes, 0, 6);
            }

            Console.WriteLine(Encoding.UTF8.GetString(XmlBytes));

            SourceSocket.Send(Packet.Serialize(MessageFlag.ShoutcastXmlMetadata, XmlBytes));
        }
Esempio n. 19
0
        private void Form6_Load(object sender, EventArgs e)
        {
            this.ClientSize      = new System.Drawing.Size(900, 550);
            this.BackgroundImage = Properties.Resources.BackgroundImage;
            SetFont();

            stream = clientSocket.GetStream(); //스트림 읽음
            Ranking state = new Ranking();     //랭킹 먼저 서버에 요구

            state.Type = (int)PacketType.랭킹;
            Packet.Serialize(state).CopyTo(this.sendbuffer, 0);
            stream.Write(this.sendbuffer, 0, this.sendbuffer.Length);
            this.stream.Flush();
            resetBuffer(sendbuffer);

            //해당 컴퓨터 ip주소 알아내기!! _ 0613
            IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress address in localIP)
            {
                if (address.AddressFamily == AddressFamily.InterNetwork)
                {
                    IP = address.ToString();
                }
            }
            //MessageBox.Show(IP);

            Thread t_handler = new Thread(setFianl);  //서버에서 랭킹, 프로필 받기 위해

            t_handler.IsBackground = true;
            t_handler.Start();
        }
Esempio n. 20
0
    public void OnShowCardName()
    {
        var msg = new Message();

        msg.action = Action.ShowCardName;
        SendMessage(Packet.Serialize(msg));
    }
Esempio n. 21
0
    private void UnhilightCard()
    {
        var msg = new Message();

        msg.action = Action.RemoveHilightCard;
        SendMessage(Packet.Serialize(msg));
    }
Esempio n. 22
0
        private void SelectPage(int pptNum)
        {
            lockPptNum  = pptNum;
            lockPageNum = ppt[pptNum].ActiveWindow.Selection.SlideRange.SlideNumber;

            ///lock한 ppt와page 넘버 서버에게전송 //packetType = LOCK
            try
            {
                Console.WriteLine("select");
                byte[] buffer = new byte[1024 * 4];
                lockPacket         = new LockPacket();
                lockPacket.type    = (int)PacketType.LOCK;
                lockPacket.pptNum  = pptNum;
                lockPacket.pageNum = lockPageNum;

                Packet.Serialize(lockPacket).CopyTo(buffer, 0);
                stream.Write(buffer, 0, buffer.Length);

                stream.Flush();
            }
            catch (Exception e)
            {
                Console.WriteLine("SelectPage() 에러 : " + e.Message);
            }
        }
Esempio n. 23
0
        private void timer1_Tick(object sender, EventArgs e)        // 남은 시간 표시
        {
            if (timeSec > 0)
            {
                timeSec--;
                int minute = timeSec / 60;
                int second = timeSec % 60;
                time.Text = string.Format("{0:0#} : {1:0#}", minute, second);
                return;
            }
            if (timeSec <= 0 && client_number == turnClientNum)          // 제한 시간 초과시 턴 변경 요청
            {
                TurnChange turnPacket = new TurnChange();
                turnPacket.Type = (int)PacketType.정답;

                turnPacket.turn      = turnClientNum;
                turnPacket.clientNum = client_number;
                turnPacket.Correct   = false;
                turnPacket.message   = "***   제한 시간이 초과되었습니다.   ***";
                turnPacket.score     = 0;
                turnPacket.turnCount = turnCount;
                Packet.Serialize(turnPacket).CopyTo(this.sendbuffer, 0);

                stream.Write(this.sendbuffer, 0, this.sendbuffer.Length);
                this.stream.Flush();
                resetBuffer(sendbuffer);
            }
        }
Esempio n. 24
0
        /*2017-06-09추가
         *한 획을 그을 때마다 저장한 그림을 서버에 전송해준다.*/
        private void sendPictuer()
        {
            byte[] sendBuffer = new byte[1024 * 4];
            //////////////////////////////   그림 파일 정보 전송   //////////////////////////////
            ClientDrawingInfo drawInfo = new ClientDrawingInfo();

            drawInfo.Type      = (int)PacketType.그림정보;
            drawInfo.clientNum = client_number;
            Packet.Serialize(drawInfo).CopyTo(sendBuffer, 0);
            stream.Write(sendBuffer, 0, sendBuffer.Length);
            stream.Flush();
            //////////////////////////////   그림 파일 전송   //////////////////////////////
            ClientDrawing draw     = new ClientDrawing();
            FileInfo      file     = new FileInfo(Environment.CurrentDirectory + "\\UserImage\\" + client_number + "Turn.jpg");
            FileStream    fileStrm = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);
            BinaryReader  reader   = new BinaryReader(fileStrm);


            int count = (int)(file.Length) / (1024) + 1;

            for (int i = 0; i < count; i++)
            {
                draw.buffer    = reader.ReadBytes(1024);
                draw.count     = count;
                draw.Type      = (int)PacketType.그림;
                draw.clientNum = client_number;
                Packet.Serialize(draw).CopyTo(sendBuffer, 0);
                stream.Write(sendBuffer, 0, sendBuffer.Length);
                this.stream.Flush();
                resetBuffer(sendBuffer);
            }
            fileStrm.Close();
            //////////////////////////////////////////////////////////////////////////////////
        }
Esempio n. 25
0
        private void SaveTime()
        {
            byte[] buffer = new byte[1024 * 4];

            // 1. connect to server
            //TcpClient client = new TcpClient("10.63.60.79", 9999);
            //if (!clientSocket.Client.Connected)
            //    clientSocket.Connect(serverAddr, 9999);
            NetworkStream stream = clientSocket.GetStream();

            // 2. send the packet
            Logout logout = new Logout();

            logout.packet_Type = (int)PacketType.Logout;
            logout.id_str      = myid;
            logout.timeleft    = string.Format("{0}:{1}:{2}", TimeLeft.hour, TimeLeft.min, TimeLeft.sec);
            //memberRegister.nickname_str = textBox5.Text.Trim();
            Packet.Serialize(logout).CopyTo(buffer, 0);
            stream.Write(buffer, 0, buffer.Length);

            Array.Clear(buffer, 0, buffer.Length);

            //int bytesRead = stream.Read(buffer, 0, buffer.Length);
            //LogoutResult loResult = (LogoutResult)Packet.Deserialize(buffer);
            //stream.Close();
        }
        private static void ProcessData(object p, object ep)
        {
            Data.Packet packet   = (Data.Packet)p;
            IPEndPoint  endPoint = (IPEndPoint)ep;

            Console.WriteLine("ID: {0}, data: {1}, answer: {2}, operation: {3}", packet.ID, packet.Data, packet.OD, packet.OP);

            if (packet.OP == OP_Enum.REGISTER && packet.OD == OD_Enum.REQUEST)
            {
                Packet ackPacket = new Packet(packet.ID, OD_Enum.NULL, OP_Enum.ACK);
                string ackString = ackPacket.Serialize();
                byte[] bytesAck  = Encoding.UTF8.GetBytes(ackString);
                _listener.Send(bytesAck, bytesAck.Length, endPoint);
                Console.Write("Operation: {0}, answer: {1}, id: {2}, data: {3}", packet.OP, packet.OD, packet.ID, packet.Data);
                Register(packet, endPoint);
            }
            if (packet.OP == OP_Enum.GUESS)
            {
                Packet ackPacket = new Packet(packet.ID, OD_Enum.NULL, OP_Enum.ACK);
                string ackString = ackPacket.Serialize();
                byte[] bytesAck  = Encoding.UTF8.GetBytes(ackString);
                _listener.Send(bytesAck, bytesAck.Length, endPoint);
                Guessing(packet, endPoint);
            }
        }
        public void SendEmergencyWarning(byte id)
        {
            Packet p = new Packet();

            byte[] message = p.Serialize(0xC9, null);
            tcpStream.Write(message, 0, message.Length);
        }
Esempio n. 28
0
    public void StartClient()
    {
        // Connect to a remote device.
        try {
            // Establish the remote endpoint for the socket.
            // The name of the
            // remote device is "host.contoso.com".
            IPEndPoint remoteEP = new IPEndPoint(iPAddress, port);

            //// Create a TCP/IP socket.
            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Connect to the remote endpoint.
            client.BeginConnect(remoteEP,
                                new AsyncCallback(ConnectCallback), client);
            connectDone.WaitOne();

            // Send test data to the remote device.
            publicPostData clientPostData = new publicPostData();
            clientPostData.packet_Type = (int)ClientPacketType.LoadBLEList;
            clientPostData.data        = 0;
            Send(client, Packet.Serialize(clientPostData));
            sendDone.WaitOne();

            // Receive the response from the remote device.
            Receive(client);
            //receiveDone.WaitOne();

            // Write the response to the console.
            Console.WriteLine("Response received : {0}", response);
        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }
    }
Esempio n. 29
0
        private void MoveToLobby(Connection connection)
        {
            int id = -1;

            lock (_players)
            {
                if (_players.ContainsKey(connection))
                {
                    id = _players[connection].id;
                    _players.Remove(connection);
                }
            }

            lock (_gameClients)
            {
                _gameClients.Remove(connection);
            }

            lock (_lobbyClients)
            {
                _lobbyClients.Add(connection);
            }

            if (id != -1)
            {
                BroadCastGame(Packet.Serialize(new PlayerDisconnectPacket(id)));
            }
        }
Esempio n. 30
0
 public void BroadCastGame(byte[] data)
 {
     // new Thread(() =>
     // {
     lock (_gameClients)
     {
         for (int i = 0; i < _gameClients.Count; i++)
         {
             try
             {
                 _gameClients[i].Send(data);
             }
             catch (Exception)
             {
                 lock (_players)
                 {
                     int id = _players[_gameClients[i]].id;
                     _gameClients.RemoveAt(i--);
                     BroadCastGame(Packet.Serialize(new PlayerDisconnectPacket(id)));
                 }
             }
         }
     }
     // }).Start();
 }
Esempio n. 31
0
 public int SendPacket(Packet.Packet packet, EndPoint dest)
 {
     return Socket.SendTo(packet.Serialize(), dest);
 }