Windows8 StreamSocket Client

        private StreamSocket clientSocket = new StreamSocket();
        private HostName serverHost;

        private string serverHostnameString;
        private string serverPort;

        private bool connected = false;

        private async void Connect_Click(object sender, RoutedEventArgs e)
        {
            if (connected)
            {
                this.StatusText.Text = "Already connected";
                return;
            }

            try
            {
                this.StatusText.Text = "Trying to connect ...";

                serverHost = new HostName(this.ServerHostname.Text);
                
                await clientSocket.ConnectAsync(serverHost, this.ServerPort.Text);
                connected = true;

                this.StatusText.Text = "Connection established" + Environment.NewLine;
            }
            catch (Exception exception)
            {
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                    throw;

                clientSocket.Dispose();
                clientSocket = null;

            }
        }

        public WorkItemPriority WorkItemPriority = WorkItemPriority.Normal;
        public IAsyncAction ThreadPoolWorkItem;

        private async void ReceiveMessage_Background()
        {
            this.ThreadPoolWorkItem = ThreadPool.RunAsync(
                async (source) =>
                {
                    if (connected)
                    {
                        DataReader reader = new DataReader(clientSocket.InputStream);
                        try
                        {
                            this.StatusText.Text = "Trying to receive data ...";

                            while (true)
                            {
                                // Read first 4 bytes (length of the subsequent string).
                                uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
                                if (sizeFieldCount != sizeof(uint))
                                    return;
                                uint stringLength = reader.ReadUInt32();

                                // Read the string.
                                uint actualStringLength = await reader.LoadAsync(stringLength);
                                if (stringLength != actualStringLength)
                                    return;
                                string recMsg = reader.ReadString(actualStringLength);

                                Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => 
                                {
                                    this.OutputView.Text = recMsg;
                                });
                            }
                        }catch (Exception exception){ }

                    }
                },
            WorkItemPriority);

            // Register a completed-event handler to run when the work item finishes or is canceled.
            this.ThreadPoolWorkItem.Completed = new AsyncActionCompletedHandler(
                (IAsyncAction source, AsyncStatus status) =>
                {

                });

        }

        private async void Send_Click(object sender, RoutedEventArgs e)
        {
            if (!connected)
            {
                this.StatusText.Text = "Must be connected to send!";
                return;
            }

            try
            {
                OutputView.Text = "";
                StatusText.Text = "Trying to send data ...";

                string sendData = this.SendText.Text;
                DataWriter writer = new DataWriter(clientSocket.OutputStream);
                //获取字符串的大小
                uint msgLength = writer.MeasureString(sendData);
                writer.WriteUInt32(msgLength);

                //写入需要发送的字符串
                writer.WriteString(sendData);

                //将缓冲区中的数据提交到备份存储区
                await writer.StoreAsync();
                await writer.FlushAsync();

                writer.DetachStream();
                writer.Dispose();

                this.StatusText.Text = "Data was sent" + Environment.NewLine;

                //分离数据流,随即关闭
                writer.DetachStream();
                writer.Dispose();
            }
            catch (Exception exception)
            {
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                    throw;
                clientSocket.Dispose();
                clientSocket = null;
                connected = false;
            }

            ReceiveMessage_Background();
        }

 

posted on 2013-03-28 09:30  JackSlaterYu  阅读(265)  评论(0编辑  收藏  举报