標籤:style blog http color os 使用 io ar for
本例用WPF程式做伺服器端,windows phone程式做用戶端。我們使用基於UDP協議的Socket通訊。更多關於socket資訊請查看:http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket(v=vs.110).aspx
我們使用DatagramSocket類完成UDP通訊功能。
具體代碼如下:(前台代碼就不帖出來了,下面只給出後台代碼和一些注釋。完整原始碼會在論壇發出來,地址在文章最後。)
socket通訊聊天windows phone 用戶端
public sealed partial class MainPage : Page{// DatagramSocket 支援使用 UDP 資料報套接的網路通訊DatagramSocket udpSocket = null;//定義本地連接埠號碼const string LOCAL_PORT = “12200″;public MainPage(){this.InitializeComponent();this.NavigationCacheMode = NavigationCacheMode.Required;}bool isUdpSocketInitializzed = false; //表示是否初始化過//若要接收 DatagramSocket 對象上的資料,應用程式必須將 MessageReceived 事件分配給事件//處理常式,然後調用 BindEndpointAsync 或 BindServiceNameAsync 方法將 DatagramSocket//綁定到本地服務名或 UDP 連接埠上。ConnectAsync 方法還會導致綁定操作。//寫入由一個 GetOutputStreamAsync 方法返回的流也將會導致綁定操作。//然後 DatagramSocket 可以接收資料報。protected async override void OnNavigatedTo(NavigationEventArgs e){if (!isUdpSocketInitializzed){udpSocket = new DatagramSocket();//定義在DatagramSocket對象上接受訊息的事件udpSocket.MessageReceived += udpSocket_MessageReceived;//啟動DatagramSocket本地服務名的綁定操作await udpSocket.BindServiceNameAsync(LOCAL_PORT);// 標誌初始已完成isUdpSocketInitializzed = true;}}async void udpSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args){//擷取DatagramSocket,以擷取從DatagramSocket對象上的的遠程網路目標接受到的傳入資料var reader = args.GetDataReader();// 資料長度uint len = reader.UnconsumedBufferLength;// 讀取內容string message = reader.ReadString(len);// 擷取主機的IP地址和連接埠號碼string host = string.Format(“{0}:{1}”, args.RemoteAddress.DisplayName, args.RemotePort);await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>{lbMessages.Items.Add(“來自” + host + “的訊息:\n” + message);});}private async void btnSend_Click(object sender, RoutedEventArgs e){if (string.IsNullOrWhiteSpace(txtToSend.Text) || string.IsNullOrWhiteSpace(txtRemoteIP.Text) || string.IsNullOrWhiteSpace(txtRemotePort.Text)){return;}// 擷取輸出資料流的引用HostName remoteHost = new HostName(txtRemoteIP.Text);IOutputStream outStream = await udpSocket.GetOutputStreamAsync(remoteHost, txtRemotePort.Text);// 發送訊息DataWriter writer = new DataWriter(outStream);//設定字元編碼writer.UnicodeEncoding = UnicodeEncoding.Utf8;//將字串值寫入輸出資料流writer.WriteString(txtToSend.Text);// 提交資料await writer.StoreAsync();//釋放writer.DetachStream();writer.Dispose();tbMessage.Text = “已發送。”;txtToSend.Text = “”;}
socket通訊聊天WPF伺服器端:
public partial class MainWindow : Window{UdpClient udpClnt = null;const int LOCAL_PORT = 9899;//本地連接埠CancellationTokenSource cancelSrc = null;public MainWindow(){InitializeComponent();this.Closing += (a, b) =>{if (udpClnt != null){try{udpClnt.Close();}catch (SocketException sex){System.Diagnostics.Debug.WriteLine(sex.Message);}}};}private async void DoReceiveMsg(){while (!cancelSrc.IsCancellationRequested){try{var result = await udpClnt.ReceiveAsync();// 遠程主面資訊string host = string.Format(“{0}:{1}”, result.RemoteEndPoint.Address.ToString(), result.RemoteEndPoint.Port);// 讀取訊息string msg = Encoding.UTF8.GetString(result.Buffer);// 顯示接到的資訊await Dispatcher.BeginInvoke(new Action(() =>{this.lbMessages.Items.Add(“來自” + host + “的訊息:\n” + msg);}));}catch{continue;}}}private void btnEnableRecv_Click(object sender, RoutedEventArgs e){CheckUdpClient();// 開始非同步接收訊息cancelSrc = new CancellationTokenSource();Task runTask = new Task(new Action(DoReceiveMsg), cancelSrc.Token);try{runTask.Start();//啟動背景工作tbMessage.Text = “後台接收已開啟。”;btnEnableRecv.IsEnabled = false;btnDisableRecv.IsEnabled = true;}catch (TaskCanceledException){tbMessage.Text = “後台接收任務已取消。”;}catch (Exception ex){System.Diagnostics.Debug.WriteLine(ex.Message);}}/// <summary>/// 檢測UdpClient對象是否已建立/// </summary>private void CheckUdpClient(){if (udpClnt == null) udpClnt = new UdpClient(LOCAL_PORT);}private void btnDisableRecv_Click(object sender, RoutedEventArgs e){// 取消背景工作if (cancelSrc != null){cancelSrc.Cancel();btnEnableRecv.IsEnabled = true;btnDisableRecv.IsEnabled = false;tbMessage.Text = “已取消後台接收訊息。”;}}private async void btnSend_Click(object sender, RoutedEventArgs e){if (string.IsNullOrWhiteSpace(txtToSend.Text)){return;}CheckUdpClient();// 驗證是否設定遠程地址和連接埠IPAddress ip;int remotePort;if (!IPAddress.TryParse(txtRemoteIP.Text,out ip)){MessageBox.Show(“請輸入遠程IP地址。”); return;}if (!int.TryParse(txtRemotePort.Text, out remotePort)){MessageBox.Show(“請輸入遠程連接埠號碼。”); return;}// 驗證輸入的連接埠號碼是否合法if (remotePort < IPEndPoint.MinPort || remotePort > IPEndPoint.MaxPort){MessageBox.Show(string.Format(“連接埠號碼的有效範圍在{0}到{1}。”, IPEndPoint.MinPort, IPEndPoint.MaxPort));return;}// 開始發送訊息byte[] buffer = Encoding.UTF8.GetBytes(txtToSend.Text);// 建立遠程終結點IPEndPoint remote = new IPEndPoint(ip, remotePort);object contentTemp = btnSend.Content;try{btnSend.Content = “正在發送”;btnSend.IsEnabled = false;await udpClnt.SendAsync(buffer, buffer.Length, remote);txtToSend.Clear();tbMessage.Text = “已發送。”;}catch (Exception ex){tbMessage.Text = “訊息發送失敗。”;System.Diagnostics.Debug.WriteLine(ex.Message);}finally{// 發送完畢btnSend.Content = contentTemp;btnSend.IsEnabled = true;}}
小夢 windows phone 8.1開發:socket通訊聊天原始碼下載:點我下載哦
windows phone 8.1開發:socket通訊聊天