Introduced
Re-imagine Windows 8 Store Apps after a task
Control channel (Controlchannel)
Example
1, client and server to do Controlchannel communication key code
Controlchannelhelper/appcontext.cs
* * This example uses global static variables to share information about the app and task so that background tasks can get information about the app. *
Note:
* can also be achieved through Windows.ApplicationModel.Core.CoreApplication.Properties save data to implement the information sharing of app and task
* *
using System.Collections.Concurrent;
Using Windows.Networking.Sockets;
Namespace Controlchannelhelper
{public
class Appcontext
{
///<summary>
///from Controlchannel received data
///</summary> public
static concurrentqueue<string> MessageQueue = new Concurrentqueue<string> ();
<summary>
///Client socket
///</summary> public
static Streamsocket clientsocket;
}
}
Controlchannelhelper/socketcontrolchannel.cs
* * Implement a Socket TCP communication controlchannel,client will receive data in real time in this controlchannel * NOTE: * WIN8 client and Socket server cannot be deployed in On the same machine, otherwise throws an exception: {The referenced object type does not support the attempted operation.
(Exception from hresult:0x8007273d)}
* * using System;
Using System.Threading.Tasks;
Using Windows.ApplicationModel.Background;
Using Windows.foundation;
Using Windows.networking;
Using Windows.Networking.Sockets;
Using Windows.Storage.Streams;
Namespace Controlchannelhelper {public class Socketcontrolchannel:idisposable {//Controlchannel
Public Controlchanneltrigger Channel {get; set;}
Client socket private Streamsocket _socket;
Used to send data private datawriter _datawriter;
Used to receive data private DataReader _datareader;
Send heartbeat intervals to the server in minutes, min 15 minutes private uint _serverkeepaliveinterval = 15;
Controlchannel Identity private String _channelid = "Mycontrolchannel";
Public Socketcontrolchannel () { Public async task<string> CreateChannel () {Dispose (); try {//instantiate a controlchannel Channel = new Controlchanneltrigger (_channelid,
_serverkeepaliveinterval, Controlchanneltriggerresourcetype.requesthardwareslot);
catch (Exception ex) {Dispose (); Return ' Control channel creation failed: ' + ex.
ToString (); //Register the background task used to send heartbeat to the server socket, need to do related configuration in manifest var keepalivebuilder = new BACKGROUNDTASKB
Uilder ();
Keepalivebuilder.name = "Mycontrolchannelkeepalive"; Note: If the WebSocket protocol is gone, the system has built-in logic for sending a heartbeat, which is specified here directly as Windows.Networking.Sockets.WebSocketKeepAlive Keepalivebu Ilder.
Taskentrypoint = "Backgroundtasklib.controlchannelkeepalive"; Keepalivebuilder.settrigger (Channel.keepalivetrigger); triggered when the heartbeat interval is sent, this example is 15 minutes KEEPALIVEBUILDER.REgister (); Register for the background task to display notifications to users, need to do related configuration in manifest//view more highlights in this column: Http://www.bianceng.cnhttp://www.bianceng.cn/Programming/net
/var pushnotifybuilder = new Backgroundtaskbuilder ();
Pushnotifybuilder.name = "Mycontrolchannelpushnotification";
Pushnotifybuilder.taskentrypoint = "Backgroundtasklib.controlchannelpushnotification"; Pushnotifybuilder.settrigger (Channel.pushnotificationtrigger);
The Pushnotifybuilder.register () is triggered when the pushed data is received in the Controlchannel;
try {_socket = new streamsocket ();
Appcontext.clientsocket = _socket;
In Controlchannel, the Streamsocket communication Channel.usingtransport (_socket) is specified; The client socket connects to the server socket await _socket.
ConnectAsync (New HostName ("192.168.6.204"), "3366"); Start waiting for data pushed over Controlchannel, if WIN8 client and socket SERVer is deployed on the same machine, the exception is thrown here controlchanneltriggerstatus status = channel.waitforpushenabled (); if (status!= controlchanneltriggerstatus.hardwareslotallocated && status!= controlchanneltriggerstatus.so ftwareslotallocated) return "Control channel creation failed:" + status.
ToString (); Send data to server _datawriter = new DataWriter (_socket.
OutputStream);
String message = "Hello" + DateTime.Now.ToString ("hh:mm:ss") + "^";
_datawriter.writestring (message);
await _datawriter.storeasync ();
Receive data Receivedata ();
catch (Exception ex) {Dispose (); Return ' Control channel creation failed: ' + ex.
ToString ();
return "OK";
//start receiving this data private void Receivedata () {UINT MAXBUFFERLENGTH = 256;
Try {var buffer = new Windows.Storage.Streams.Buffer (maxbufferlength); var asyncoperation = _socket.
Inputstream.readasync (buffer, maxbufferlength, inputstreamoptions.partial); asyncoperation.completed = (Iasyncoperationwithprogress<ibuffer, uint> asyncinfo, AsyncStatus AsyncStatus) = > {switch (asyncstatus) {case ASYNCST ATUs.
Completed:case AsyncStatus.Error:try {
Ibuffer bufferread = Asyncinfo.getresults ();
UINT bytesread = bufferread.length;
_datareader = Datareader.frombuffer (Bufferread);
The data received the completion of receivecompleted (Bytesread); catch (Exception Ex) {AppContext.MessageQueue.Enqueue (ex.
ToString ());
} break;
Case AsyncStatus.Canceled:AppContext.MessageQueue.Enqueue ("canceled when receiving data");
Break
}
}; The catch (Exception ex) {AppContext.MessageQueue.Enqueue (ex).
ToString ()); } public void receivecompleted (UINT bytesread) {//Get the data received this time uint
Bufferlength = _datareader.unconsumedbufferlength;
String message = _datareader.readstring (bufferlength);
The received data is put into memory, which is handled by Pushnotificationtrigger triggered by the background (and can also be processed here) AppContext.MessageQueue.Enqueue (message);
Start receiving next data receivedata (); }//Free resources public void Dispose () {lock (this) {if (_datawriter!= null) {
try {_datawriter.detachstream ();
_datawriter = null;
\ catch (Exception ex) {}}
if (_datareader!= null) {try {
_datareader.detachstream ();
_datareader = null;
catch (Exception exp) {}} if (_socket!= null) {_socket.
Dispose ();
_socket = null;
} if (Channel!= null) {channel.dispose (); CHannel = null; }
}
}
}
}
2. Service End
Backgroundtasklib/controlchannelkeepalive.cs