New Fashion Windows 8 Development (38): chat program

Source: Internet
Author: User
Tags blank page

Socket has always been a tough thing, but we still need to talk about it. In fact, we can use WCF to implement the network communication function.

Today, let's talk about the datagramsocket class. Although this name seems a little strange, in fact, to put it bluntly, this guy just changed to a "vest", essentially UDP transmission, the most suitable method is to transmit some simple text information, so it is quite appropriate to get a chat program.

Because Windows "brick-and-mortar" applications usually have an application window full of the entire screen, and sometimes may be mounted to one side of the screen, in order to prove that the datagramsocket is a UDP socket, we use the Windows Store application at one end, the other end uses WPF for development. You can see the communication between the two.

To facilitate testing on the local machine, you can use a simulator on the Windows Store application. The simulator is simulated based on the current system of the Local Machine. Therefore, the IP address can be 127.0.0.1.

The following describes how to run an application.

 

 

In order not to produce garbled, both sides of the communication are using UTF-8 encoding, so that they have a tacit understanding.

 

First, implement Windows Store.

For the homepage layout, see the following XAML. I will not explain it any more.

<Page X: class = "wstoresocketapp. mainpage "xmlns =" http://schemas.microsoft.com/winfx/2006/xaml/presentation "xmlns: x =" http://schemas.microsoft.com/winfx/2006/xaml "xmlns: Local =" using: wstoresocketapp "xmlns: D =" http://schemas.microsoft.com/expression/blend/2008 "xmlns: MC =" http://schemas.openxmlformats.org/markup-compatibility/2006 "MC: ignorable = "D"> <page. resources> <style X: Key = "tbfield" targettype = "t Extblock "> <setter property =" fontsize "value =" 20 "/> <setter property =" verticalignment "value =" center "/> <setter property =" margin "value = "2, 0, 6, 0 "/> </style> </page. resources> <grid background = "{staticresource applicationpagebackgroundthemebrush}"> <stackpanel> <! -- Used to display received messages --> <ListBox X: Name = "lbrecmessages" Height = "300"/> <grid margin = ","> <grid. columndefinitions> <columndefinition width = "Auto"/> <columndefinition width = "Auto"/> <columndefinition/> </grid. columndefinitions> <textblock grid. column = "0" style = "{staticresource tbfield}" text = "remote host:"/> <textbox X: Name = "txtremote" grid. column = "1" width = "260" horizontalalignment = "L EFT "text =" 127.0.0.1 "/> <textblock grid. column = "2" style = "{staticresource tbfield}" text = "remote port:"/> <textbox X: Name = "txtport" grid. column = "3" width = "90" horizontalalignment = "Left"/> </GRID> <! -- Used to enter the message to be sent --> <textbox X: Name = "txtmessageinput" margin = "180," Height = ""/> <stackpanel margin =, "orientation =" horizontal "> <button content =" Send message "margin =", "click =" onsend "/> <textblock margin =, 0, 2 "X: Name =" tbmessage "fontsize =" 22 "/> </stackpanel> </GRID> </Page>

The hidden code is as follows: [C #]

Using system; using system. collections. generic; using system. io; using system. LINQ; using Windows. foundation; using Windows. foundation. collections; using Windows. UI. XAML; using Windows. UI. XAML. controls; using Windows. UI. XAML. controls. primitives; using Windows. UI. XAML. data; using Windows. UI. XAML. input; using Windows. UI. XAML. media; using Windows. UI. XAML. navigation; using Windows. storage. streams; using Windows. netw Orking; using Windows. Networking. Sockets; namespace wstoresocketapp {// <summary> /// you can use it to itself or navigate to a blank page inside the frame. /// </Summary> Public sealed partial class mainpage: Page {datagramsocket mysocket = NULL; const string local_port = "9700"; // Local Port Public mainpage () {This. initializecomponent ();} protected async override void onnavigatedto (navigationeventargs e) {If (mysocket = NULL) {mysocket = new datagramsocket (); mysocket. messagereceived + = mysocket_messagereceived; await mysocket. bindservicenameasync (Local_port) ;}} async void mysocket_messagereceived (datagramsocket sender, datagramsocketmessagereceivedeventargs ARGs) {var reader = args. getdatareader (); reader. unicodeencoding = unicodeencoding. utf8; string MSG = reader. readstring (reader. unconsumedbufferlength); await dispatcher. runasync (windows. UI. core. coredispatcherpriority. normal, () => {This. lbrecmessages. items. add (MSG) ;});} private YNC void onsend (Object sender, routedeventargs e) {If (mysocket = NULL) return; If (this.txt remote. TEXT = "" | this.txt port. TEXT = "") {return;} hostname host = new hostname(this.txt remote. text); var outstream = await mysocket. getoutputstreamasync (host, this.txt port. text); datawriter writer = new datawriter (outstream); // write data into the stream writer.writestring(this.txt messageinput. text); await writer. s Toreasync (); writer. detachstream (); tbmessage. Text = "The message has been sent. "; Txtmessageinput. Text = "";}}}

Note the following:

1. register the messagereceived event before calling bindservicenameasync or bindendpointasync to bind the local endpoint.

2. Do not close the output stream after sending the message. Otherwise, an exception will occur when sending the message again. Closing the stream is almost equivalent to closing the socket.

            writer.WriteString(this.txtMessageInput.Text);            await writer.StoreAsync();            writer.DetachStream();

After writestring is complete, the data has not been sent. After storeasync is called, the data is submitted to the stream. After use, call detachstream to separate datawriter from the stream, but do not close the stream.

 

Item 2: WPF end.

The interface layout is very simple, and The XAML is highly portable. Therefore, copy the XAML directly from the above application to the mainwindow. XAML of the WPF project, and then change it slightly.

<Window X: class = "wpfudpsocketapp. mainwindow "xmlns =" http://schemas.microsoft.com/winfx/2006/xaml/presentation "xmlns: x =" http://schemas.microsoft.com/winfx/2006/xaml "Title =" client "Height =" 500 "width =" 800 "> <window. resources> <style X: Key = "tbfield" targettype = "{X: type textblock} "> <setter property =" fontsize "value =" 20 "/> <setter property =" verticalignment "value =" center "/> <setter property =" margin" V Alue = "2, 0, 6, 0"/> </style> </window. Resources> <grid> <stackpanel> <! -- Used to display received messages --> <ListBox X: Name = "lbrecmessages" Height = "200"/> <grid margin = ","> <grid. columndefinitions> <columndefinition width = "Auto"/> <columndefinition width = "*"/> <columndefinition width = "Auto"/> <columndefinition width = "*"/> </ grid. columndefinitions> <textblock grid. column = "0" style = "{dynamicresource tbfield}" text = "remote host:"/> <textbox X: Name = "txtremote" grid. column = "1" width = "260" H Orizontalalignment = "Left" text = "127.0.0.1"/> <textblock grid. column = "2" style = "{staticresource tbfield}" text = "remote port:"/> <textbox X: Name = "txtport" grid. column = "3" width = "90" horizontalalignment = "Left"/> </GRID> <! -- Used to enter the message to be sent --> <textbox X: Name = "txtmessageinput" margin = "," Height = "95"/> <stackpanel margin =, "orientation =" horizontal "> <button content =" Send message "margin =", "click =" onsend "/> <textblock margin =, 0, 2 "X: Name =" tbmessage "fontsize =" 22 "/> </stackpanel> </GRID> </WINDOW>

 

The subsequent code is the same as the previous. NET development, and can be completed with the udpclient class.

Using system; using system. collections. generic; using system. LINQ; using system. text; using system. threading. tasks; using system. windows; using system. windows. controls; using system. windows. data; using system. windows. documents; using system. windows. input; using system. windows. media; using system. windows. media. imaging; using system. windows. navigation; using system. windows. shapes; using system. net; using system. io; Using system. net. sockets; namespace wpfudpsocketapp {// <summary> // mainwindow. interaction logic of XAML // </Summary> Public partial class mainwindow: window {udpclient mclient = NULL; const int local_port = 9800; // The Local Port Public mainwindow () {initializecomponent (); this. mclient = new udpclient (local_port); this. loaded + = (a, B) => {task. run (new action (this. receivemessage) ;};} private void onsend (Object Sender, routedeventargs e) {int rmport = int. minvalue; If (mclient! = NULL & this.txt messageinput. Text! = "" & This.txt remote. Text! = "" & Int. tryparse (txtport. text, out rmport) {byte [] buffer = encoding.utf8.getbytes(this.txt messageinput. text); mclient. send (buffer, buffer. length, this.txt remote. text, rmport); tbmessage. TEXT = "The message has been sent. "; Txtmessageinput. Clear () ;}} private void receivemessage () {ipendpoint Ep = new ipendpoint (IPaddress. Any, 0); While (mclient! = NULL) {byte [] buffer = mclient. receive (ref EP); string MSG = encoding. utf8.getstring (buffer); dispatcher. begininvoke (new action () => {This. lbrecmessages. items. add (MSG) ;}, null );}}}}

Start the two applications at the same time to test. Note that the remote port must be set to the correct port. If the other application listens on the port, you just need to enter the port number.

The code is then uploaded to the resource.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.