在Windows Store應用程式中使用Stram Socket與案頭用戶端進行通訊,一直沒弄成功,總讓俺覺得很震精,怎麼會不成功呢。後來經過幾回測試發現,原來是在DataReader那裡出了問題,總算弄成了。
Stream Socket通常用於傳輸一些比較長的資料,如檔案。但這裡為了使示範變得更容易理解,我傳輸了一段字元。
首先,我們用WinForm做一個伺服器端。介面不複雜,目的是偵聽串連,收到傳入的用戶端串連後,向用戶端發送一條字串訊息。
處理的邏輯代碼如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.Net; using System.Net.Sockets; namespace TestServerApp { public partial class Form1 : Form { TcpListener m_Listener = null;//用於監聽連結 TcpClient m_Client = null;//傳入的用戶端 public Form1() { InitializeComponent(); this.btnStart.Enabled = true; this.btnStop.Enabled = false; } /// <summary> /// 向用戶端發送字串 /// </summary> private void SendMessage(TcpClient client) { using (var stream = client.GetStream()) { byte[] buffer = Encoding.UTF8.GetBytes("奔,不停地奔,奔向傳說中的荒原;飛,不停地飛,飛向天空的那一端。"); uint len = (uint)buffer.Length; // 先發送長度 stream.Write(BitConverter.GetBytes(len), 0, sizeof(uint)); // 再發送資料 stream.Write(buffer, 0, buffer.Length); } } private async void btnStart_Click(object sender, EventArgs e) { if (this.m_Listener == null) { this.m_Listener = new TcpListener(IPAddress.Parse(this.txtAddr.Text), Convert.ToInt32(this.udPort.Value)); } this.m_Listener.Start(); this.lblMsg.Text = "監聽已開始。"; this.btnStart.Enabled = false; this.btnStop.Enabled = true; try { m_Client = await m_Listener.AcceptTcpClientAsync(); SendMessage(m_Client); } catch (SocketException se) { this.lblMsg.Text = se.Message; } catch (Exception ex) { this.lblMsg.Text = ex.Message; } } private void btnStop_Click(object sender, EventArgs e) { if (m_Listener != null) { m_Listener.Stop(); this.lblMsg.Text = "監聽已停止。"; } this.btnStart.Enabled = true; this.btnStop.Enabled = false; } } }