This example uses the WPF program to do the server side, the Windows Phone program does the client. We use a UDP protocol-based socket communication. For more information on sockets see: Http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket (v=vs.110). aspx
We use the Datagramsocket class to complete the UDP communication function.
The code is as follows: (foreground code does not come out, the following only gives the background code and some comments.) The full source code will be issued in the Forum, the address at the end of the article. )
Socket communication Chat windows Phone Client
Public Sealed Partial classmainpage:page{//datagramsocket support for network traffic using UDP datagram socketsDatagramsocket Udpsocket =NULL;//define a local port numberConst stringLocal_port = "12200″; PublicMainPage () { This. InitializeComponent (); This. Navigationcachemode =navigationcachemode.required;}BOOLisudpsocketinitializzed =false;//Indicates whether the initialization has been initialized//to receive data on an Datagramsocket object, the application must assign the Messagereceived event to the event//handler, and then call the Bindendpointasync or Bindservicenameasync method to Datagramsocket//bind to the local service name or UDP port. The ConnectAsync method also causes the binding operation. //writing a stream returned by a Getoutputstreamasync method will also cause the binding operation. //then Datagramsocket can receive datagrams. protected Async Override voidonnavigatedto (NavigationEventArgs e) {if(!isudpsocketinitializzed) {Udpsocket=NewDatagramsocket ();//to define an event that accepts messages on a Datagramsocket objectUdpsocket.messagereceived + =udpsocket_messagereceived;//to start a bind operation for the Datagramsocket Local service nameawaitUdpsocket.bindservicenameasync (local_port);//flag is initially completedisudpsocketinitializzed =true;}}Async voidudpsocket_messagereceived (datagramsocket sender, Datagramsocketmessagereceivedeventargs args) {//gets the datagramsocket to get incoming data received from the remote network destination on the Datagramsocket objectvarReader =args. Getdatareader ();//Data LengthUINTLen =Reader. Unconsumedbufferlength;//Read ContentstringMessage =Reader. ReadString (len);//get the IP address and port number of the hoststringHost =string. Format ("{0}:{1} ", args. Remoteaddress.displayname, args. RemotePort);awaitDispatcher.runasync (Windows.UI.Core.CoreDispatcherPriority.Normal, () ={lbMessages.Items.Add ("from"+ Host + "message: \ n" +message);});Private Async voidBtnsend_click (Objectsender, RoutedEventArgs e) {if(string. Isnullorwhitespace (txttosend.text) | |string. Isnullorwhitespace (txtremoteip.text) | |string. Isnullorwhitespace (Txtremoteport.text)) {return;}//get a reference to the output streamHostName remotehost =NewHostName (txtremoteip.text); Ioutputstream OutStream=awaitUdpsocket.getoutputstreamasync (RemoteHost, txtremoteport.text);//Send MessageDataWriter writer =NewDataWriter (outstream);//Set character encodingWriter. UnicodeEncoding =Unicodeencoding.utf8;//writes a string value to the output streamwriter. WriteString (txttosend.text);//Submit Dataawaitwriter. Storeasync ();//Releasewriter. Detachstream (); writer. Dispose (); Tbmessage.text="has been sent. "; Txttosend.text="";}
Socket communication Chat WPF server side:
Public Partial classmainwindow:window{udpclient udpclnt=NULL;Const intLocal_port =9899;//Local PortCancellationTokenSource CANCELSRC =NULL; PublicMainWindow () {InitializeComponent (); This. Closing + = (A, b) = ={if(Udpclnt! =NULL){Try{udpclnt.close ();}Catch(SocketException Sex) {System.Diagnostics.Debug.WriteLine (Sex). Message); }}};}Private Async voiddoreceivemsg () { while(!cancelsrc.iscancellationrequested) {Try{varresult =awaitUdpclnt.receiveasync ();//Remote Main polygon informationstringHost =string. Format ("{0}:{1} ", result. RemoteEndPoint.Address.ToString (), result. Remoteendpoint.port);//reading Messagesstringmsg =Encoding.UTF8.GetString (result. Buffer);//Display the information you receivedawaitDispatcher.begininvoke (NewAction (()={ This. LBMESSAGES.ITEMS.ADD ("from" + Host + "message: \ n" +( msg);}));Catch{Continue;}}}Private voidBtnenablerecv_click (Objectsender, RoutedEventArgs e) {checkudpclient ();//start receiving messages asynchronouslyCANCELSRC =NewCancellationTokenSource (); Task RunTask=NewTask (NewAction (doreceivemsg), cancelsrc.token);Try{Runtask.start ();//start a background taskTbmessage.text ="Background receive is turned on. "; btnenablerecv.isenabled=false; btndisablerecv.isenabled=true;}Catch(taskcanceledexception) {Tbmessage.text=The background receive task has been canceled. ";}Catch(Exception ex) {System.Diagnostics.Debug.WriteLine (ex). Message);}}/// <summary>///detects if the UdpClient object has been created/// </summary>Private voidcheckudpclient () {if(Udpclnt = =NULL) Udpclnt =NewUdpClient (Local_port);}Private voidBtndisablerecv_click (Objectsender, RoutedEventArgs e) {//canceling a background taskif(Cancelsrc! =NULL) {cancelsrc.cancel (); btnenablerecv.isenabled=true; btndisablerecv.isenabled=false; Tbmessage.text="The background receive message has been canceled. ";}}Private Async voidBtnsend_click (Objectsender, RoutedEventArgs e) {if(string. Isnullorwhitespace (Txttosend.text)) {return;} Checkudpclient ();//Verify that the remote address and port are setIPAddress IP;intRemotePort;if(! Ipaddress.tryparse (Txtremoteip.text, outIP)) {MessageBox.Show ("Please enter the remote IP address. ");return;}if(!int. TryParse (Txtremoteport.text, outremoteport)) {MessageBox.Show ("Please enter the remote port number. ");return;}//Verify that the port number entered is legitimateif(RemotePort < Ipendpoint.minport | | remoteport >Ipendpoint.maxport) {MessageBox.Show (string. Format (The valid range of port numbers in {0To1}. ", Ipendpoint.minport, Ipendpoint.maxport));return;}//Start sending Messagesbyte[] buffer =Encoding.UTF8.GetBytes (txttosend.text);//To create a remote endpointIPEndPoint remote =Newipendpoint (IP, remoteport);ObjectContenttemp =btnsend.content;Try{btnsend.content="Sending"; btnsend.isenabled=false;awaitudpclnt.sendasync (buffer, buffer. Length, remote); Txttosend.clear (); Tbmessage.text="has been sent. ";}Catch(Exception ex) {Tbmessage.text="The message failed to send. ”; System.Diagnostics.Debug.WriteLine (ex. Message);}finally{//Send CompleteBtnsend.content =contenttemp;btnsend.isenabled=true;}}
Small Dream Windows Phone 8.1 development: Socket communication Chat Source code download: Click I download OH
Windows Phone 8.1 Development: Socket Communication Chat