Windows 8 Metro UDP通信通过 DatagramSocket实现行情的推送

metro UDP通信通过 DatagramSocket实现行情的推送,可以参考 Windows 8 Metro App开发[21]DatagramSocket与UDP

        private void Timer()
        {
            timerActive = new DispatcherTimer();
            timerActive.Tick += new EventHandler<object>(timer_active);
            timerActive.Interval = new TimeSpan(0, 0, 间隔时间);
            timerActive.Start();

            timerRestore = new DispatcherTimer();
            timerRestore.Tick += new EventHandler<object>(timer_Restore);
            timerRestore.Interval = new TimeSpan(0, 0, 间隔时间);
            timerRestore.Start();
        }
        DatagramSocket socket = null;//局部变量
        private void timer_active(object sender, object e)
        {
            try
            {
                if (socket != null)
                {
                    socket.Dispose();
                }
                socket = null;//局部变量
                ConnSocket(参数, 参数);
            }
            catch
            {
                ConnSocket(参数,参数);
            }
        }

        private void timer_Restore(object sender, object e)
        {
            Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                for (int i = 0; i < qis.Count; i++)
                {
                    if (qis[i].ExTime.AddSeconds(3) < DateTime.Now)
                    {

                        ListBoxItem lbi = (ListBoxItem)lb2.ItemContainerGenerator.ContainerFromIndex(qis[i].Index);
                        if (lbi != null)
                        {
                            Grid g = Utility.FindVisualElement<Grid>(lbi);
                            Grid g2 = Utility.FindVisualElement<Grid>(g);
                            g2.Background = new SolidColorBrush(Colors.Transparent);
                            TextBlock tb = Utility.FindVisualElement<TextBlock>(g2);
                            SolidColorBrush scb = double.Parse(qis[i].Close) - double.Parse(qis[i].Last) > 0 ? new SolidColorBrush(Colors.Green) : new SolidColorBrush(Colors.Red);
                            tb.Foreground = scb;
                            qis.Remove(qis[i]);
                        }
                    }
                }
            });
        }



        private async void ConnSocket(int max, string content)
        {
            try
            {
                socket = new DatagramSocket();
                if (Utility.IsConnectedToInternet())
                {
                    HostName host = new HostName("地址");
                    string port = "端口";
                    try
                    {
                        socket.MessageReceived += MessageReceived;
                        await socket.BindServiceNameAsync(port);
                        await socket.ConnectAsync(host, port);
                        //将发送内容的信息存放进Socket异步事件参数中
                        DataWriter udpWriter = new DataWriter(socket.OutputStream);
                        //把数据写入到发送流
                        udpWriter.WriteString(content);
                        //异步发送
                        await udpWriter.StoreAsync();
                        //异步刷新数据
                        await udpWriter.FlushAsync(); 
                        // this.isConnected = true;
                    }
                    catch (Exception exception)
                    {
                        if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                        {
                            socket.Dispose();
                            return;
                        }
                    }
                }
                else
                {
                    //MessageDialog dlg = new MessageDialog("未连接到网络", "友情提示");
                    //await dlg.ShowAsync();
                }
            }
            catch(Exception e)
            {
                string mm = e.ToString();

            }
        }


        async void MessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs eventArguments)
        {
            IBuffer buffer;
            try
            {
                IOutputStream outputStream = await socket.GetOutputStreamAsync(eventArguments.RemoteAddress, eventArguments.RemotePort);
                buffer = eventArguments.GetDataReader().DetachBuffer();
                await outputStream.WriteAsync(buffer);

                byte[] bytes = WindowsRuntimeBufferExtensions.ToArray(buffer, 0, (int)buffer.Length);
                string dataFromServer = Encoding.UTF8.GetString(bytes, 0, bytes.Length);//这为UDP返回的数据

                await lb2.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    ObservableCollection<Quote> quotes = (ObservableCollection<Quote>)lb2.ItemsSource;
                    ObservableCollection<Quote> q = (ObservableCollection<Quote>)JsonConvert.DeserializeObject("[" + dataFromServer + "]", typeof(ObservableCollection<Quote>));//以下编写需要操作的数据
                   
                });
            }
            catch (Exception exception)
            {
                SocketErrorStatus socketError = SocketError.GetStatus(exception.HResult);
                if (socketError == SocketErrorStatus.ConnectionResetByPeer)
                {

                }
                else if (socketError != SocketErrorStatus.Unknown)
                {

                }
                else
                {
                }
            }
            finally
            {
                socket.Dispose();
                socket = null;
            }
        }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值