首页 > 代码库 > windows phone 8.1开发:socket通信聊天
windows phone 8.1开发:socket通信聊天
本例用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 = http://www.mamicode.com/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 = http://www.mamicode.com/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通信聊天
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。