Development of New Fashion Windows 8 (40): Use of streamsocket

Source: Internet
Author: User
Tags blank page

Applications in Windows StoreProgramUsing Stram socket to communicate with the Desktop client has never been successful, and it always makes me feel shocked. How can it fail. After several tests, we found that a problem occurred in the datareader and finally got it.

Stream socket is usually used to transmit long data, such as files. However, in order to make the demo easier to understand, I transmitted a section of characters.

First, we use winform as a server. The interface is not complex. It is used to listen for connections. After receiving the incoming client connection, it sends a string message to the client.

Processing logicCodeAs follows:

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; // used to listen to tcpclient m_client = NULL; // the incoming client pub LIC form1 () {initializecomponent (); this. btnstart. enabled = true; this. btnstop. enabled = false;} // <summary> // send a string to the client /// </Summary> private void sendmessage (tcpclient client) {using (VAR stream = client. getstream () {byte [] buffer = encoding. utf8.getbytes. "); Uint Len = (uint) buffer. length; // sends the stream length first. write (bitconverter. getbytes (LEN), 0, sizeof (uint); // resend the data 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.txt ADDR. text), convert. toint32 (this. udport. value);} This. m_listener.start (); this. lblmsg. tex T = "the listener has started. "; 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 = "the listener has stopped. ";}This. btnstart. Enabled = true; this. btnstop. Enabled = false ;}}}

 

Next is the Win8 app client.

Because we want to use network connection, after creating a project, open the configuration file, switch to the [function] tab, and check the network connection-related options.

 

Open the XAML Code Editor (design view) on the mainpage to provide a simple layout.

<Page X: class = "wcleintapp. mainpage "xmlns =" http://schemas.microsoft.com/winfx/2006/xaml/presentation "xmlns: x =" http://schemas.microsoft.com/winfx/2006/xaml "xmlns: Local =" using: wcleintapp "xmlns: D =" http://schemas.microsoft.com/expression/blend/2008 "xmlns: MC =" http://schemas.openxmlformats.org/markup-compatibility/2006 "MC: ignorable = "D"> <grid background = "{staticresource applicationpagebackgroundthemebrush}"> <grid. rowdefinitions> <rowdefinition Height = "Auto"/> <rowdefinition Height = "*"/> </grid. rowdefinitions> <grid. row = "0" margin = "3"> <grid. rowdefinitions> <rowdefinition Height = "Auto"/> <rowdefinition Height = "Auto"/> </grid. rowdefinitions> <grid. columndefinitions> <columndefinition width = "Auto"/> <columndefinition width = "*"/> </grid. columndefinitions> <textblock grid. row = "0" grid. column = "0" verticalalignment = "center" text = "server:"/> <textblock grid. row = "1" grid. column = "0" verticalalignment = "center" text = "port:"/> <textbox X: Name = "txtserver" grid. row = "0" grid. column = "1" margin = "2, 3"/> <textbox X: Name = "txtport" grid. row = "1" grid. column = "1" margin = "2, 3"/> </GRID> <stackpanel grid. row = "1" margin = "5"> <button content = "Connect" Click = "onconnclick" margin = "," padding = "4, 2.5 "/> <textbox X: Name =" txtrec "margin =" 5, 7, 200 "Height =" "isreadonly =" true "/> </stackpanel> </GRID> </Page>

Switch to the hidden code view to complete the functional code.

 
Using system; using system. Collections. Generic; using system. IO;
 
........
Using Windows. UI. XAML. navigation; using Windows. networking; using Windows. networking. sockets; using Windows. storage. streams; namespace wcleintapp {/// <summary> /// you can use it to itself or navigate to a blank page inside the frame. /// </Summary> Public sealed partial class mainpage: Page {streamsocket msocket = NULL; // local variable bool isconnected; // identifies whether the public mainpage () is connected () {This. initializecomponent (); this. isconnected = false;} private async void onconnclick (Object sender, routedeventargs e) {If (msocket = NULL) {msocket = new streamsocket ();} // Connect if (this. isconnected = false) {hostname hserver = new host Name (txtserver. text); try {await msocket. connectasync (hserver, txtport. text); this. isconnected = true;} catch {This. isconnected = false ;}} datareader DR = new datareader (msocket. inputstream); // byteorder must be set to littleendian. Otherwise, an error occurs. byteorder = byteorder. littleendian; Dr. unicodeencoding = unicodeencoding. utf8; // encode // read the value of a uint in four bytes to know the length of the data to be received. var IL = await dr. loadasync (sizeof (uint); // If Not equal, it indicates that the read value is not a uint value, because it must be 4 bytes if (Il! = Sizeof (uint) {txtrec. Text = "The data size cannot be determined. "; Return;} // determine the Data Length in the stream. uint strlen = dr. readuint32 (); // continue to load the remaining data await dr. loadasync (strlen); txtrec. TEXT = dr. readstring (strlen); // It must be separated from the stream to avoid releasing the entire stream. detachstream (); Dr. dispose ();}}}

First run the server, enter the local IP address and listening port, and then start listening.

Run the client, enter the IP address and port of the server, and connect to the server. If the connection succeeds, the server receives the string sent by the server.

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.