Skip to content

Instantly share code, notes, and snippets.

@jgc128
Created June 23, 2013 18:49
Show Gist options
  • Save jgc128/5846070 to your computer and use it in GitHub Desktop.
Save jgc128/5846070 to your computer and use it in GitHub Desktop.
WinRT client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
namespace AzalyDC.Common.Networking
{
//public class ErrorEventArgs : EventArgs
//{
// public string Error { get; private set; }
// public ErrorEventArgs(string error)
// {
// Error = error;
// }
//}
public class Client
{
//#region Events
//public event EventHandler<ErrorEventArgs> Error;
//protected virtual void OnError(ErrorEventArgs e)
//{
// if (Error != null)
// Error(this, e);
//}
//public event EventHandler Connected;
//protected virtual void OnConnected(EventArgs e)
//{
// if (Connected != null)
// Connected(this, e);
//}
//public event EventHandler Disconnected;
//protected virtual void OnDisconnected(EventArgs e)
//{
// if (Disconnected != null)
// Disconnected(this, e);
//}
//#endregion
public Encoding Encoding;
protected StreamSocket sock;
protected DataReader reader;
protected DataWriter writer;
protected bool _isConnected;
public Client()
{
sock = new StreamSocket();
reader = new DataReader(sock.InputStream);
writer = new DataWriter(sock.OutputStream);
reader.InputStreamOptions = InputStreamOptions.Partial;
this.Encoding = Encoding.UTF8;
this._isConnected = false;
}
public async Task<bool> ConnectAsync(string Address, int Port)
{
if (_isConnected)
return true;
if (Address == "")
return false;
HostName host = new HostName(Address);
string serviceName = Port.ToString();
try
{
await sock.ConnectAsync(host, serviceName);
_isConnected = true;
return true;
}
catch
{
return false;
}
}
public void Close()
{
sock.Dispose();
}
public async Task<string> ReadAsync()
{
var bytesLoaded = await reader.LoadAsync(1024);
if (bytesLoaded == 0)
return null;
byte[] buff = new byte[bytesLoaded];
reader.ReadBytes(buff);
return this.Encoding.GetString(buff, 0, buff.Length);
}
public async Task SendAsync(string str)
{
byte[] buff = this.Encoding.GetBytes(str);
writer.WriteBytes(buff);
await writer.StoreAsync();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AzalyDC.Common.Networking
{
public class CommandReceivedEventArgs : EventArgs
{
public string Command { get; private set; }
public CommandReceivedEventArgs(string Command)
{
this.Command = Command;
}
}
public class ClientWithDelimeters : Client
{
char delimeter;
CancellationTokenSource tokenSource;
CancellationToken token;
public bool AddDelimeterToSend;
#region Events
public event EventHandler<CommandReceivedEventArgs> CommandReceived;
protected virtual void OnCommandReceived(CommandReceivedEventArgs e)
{
if (CommandReceived != null)
CommandReceived(this, e);
}
public event EventHandler Disconnected;
protected virtual void OnDisconnected(EventArgs e)
{
if (Disconnected != null)
Disconnected(this, e);
}
#endregion
public ClientWithDelimeters(char Delimeter)
{
this.delimeter = Delimeter;
AddDelimeterToSend = true;
}
public async Task SendCommandAsync(string Command)
{
if(AddDelimeterToSend)
Command += delimeter;
await SendAsync(Command);
}
public async Task SendCommandAsync(params string[] Commands)
{
StringBuilder sb = new StringBuilder();
foreach (var item in Commands)
{
sb.Append(item).Append(delimeter);
}
sb.Remove(sb.Length - 1, 1);
await SendCommandAsync(sb.ToString());
}
public void StartReceive()
{
if (_isConnected && tokenSource == null)
{
tokenSource = new CancellationTokenSource();
token = tokenSource.Token;
Task.Factory.StartNew( ()=>receiveTaskAction(token), token );
}
}
public void CancelReceive()
{
tokenSource.Cancel();
}
private async void receiveTaskAction(CancellationToken token)
{
string buff = "";
while (!token.IsCancellationRequested)
{
buff += await ReadAsync();
string[] commands = buff.Split(delimeter);
if (commands.Length > 0)
{
buff = commands[commands.Length - 1]; // Что бы не отбрасывать команды, котрые были считаны не доконца
foreach (var cmd in commands)
{
if (String.IsNullOrWhiteSpace(cmd))
continue;
OnCommandReceived(new CommandReceivedEventArgs(cmd));
}
}
}
//token.ThrowIfCancellationRequested();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment