Using the Stram socket in a Windows store application to communicate with a desktop client has not been successful, always let me feel very shocked, how will not succeed. Later, after several tests found that the original is in the DataReader there is a problem, finally made.
Stream sockets are typically used to transfer some relatively long data, such as a file. But in order for the demo to become easier to understand, I transferred a character.
First, we use WinForm to do a server side. The interface is not complex to listen for connections, and after receiving incoming client connections, send a string message to the client.
The logical code for processing is as 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;//for listening
Link TcpClient m_client = null;//incoming client public Form1 () {InitializeComponent ();
This.btnStart.Enabled = true;
this.btnStop.Enabled = false; ///<summary>///Send a string to the client///</summary> private void Sendm Essage (TcpClient client) {using (var stream = client. GetStream ()) {byte[] buffer = Encoding.UTF8.GetBytes ("Ben, keep running, run to the legendary wilderness, fly, keep flying, fly to the end of the sky.")
"); UINT LEN = (UINT) buffer.
Length; Send the length stream first.
Write (Bitconverter.getbytes (len), 0, sizeof (UINT)); The data stream is sent again. 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.txtAddr.Text), Convert.ToInt32 (This.udPort.Valu
e));
} this.m_Listener.Start (); This.lblMsg.Text = "Listening 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; The catch (Exception ex) {this.lblMsg.Text = ex.
message; }} private void Btnstop_click (object sender, EventArgs e) {if (m_list
Ener!= null) {m_listener.stop (); This.lblMsg.Text = "Listening has stopped.
";
} this.btnStart.Enabled = true;
this.btnStop.Enabled = false; }
}
}