Created
March 17, 2011 03:37
-
-
Save dragan/873786 to your computer and use it in GitHub Desktop.
A few changes to Node to show async for Jason
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Configuration; | |
using System.Net; | |
using System.Net.Sockets; | |
namespace Ketchup | |
{ | |
public class Node | |
{ | |
private byte[] buffer = new byte[1024]; | |
private int bufferSize = 1024; | |
public int Port { get; set; } | |
public string Host { get; set; } | |
private Socket Client { get; set; } | |
public string Id | |
{ | |
get { return Host + ":" + Port; } | |
} | |
public Node() : this("127.0.0.1", 5000) {} | |
public Node(string host, int port) | |
{ | |
Host = host; | |
Port = port; | |
} | |
public void Connect() | |
{ | |
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); | |
var endPoint = new IPEndPoint(IPAddress.Parse(Host), Port); | |
socket.BeginConnect(endPoint, new AsyncCallback(Connected), new NodeAsyncState { Socket = socket }); | |
} | |
public Node Request(byte[] packet, Action<byte[]> callback) | |
{ | |
Client.BeginSend(packet, 0, packet.Length, SocketFlags.None, new AsyncCallback(SendData), new NodeAsyncState { Socket = Client, Callback = callback }); | |
return this; | |
} | |
private void Connected(IAsyncResult asyncResult) | |
{ | |
var nodeAsyncState = (NodeAsyncState)asyncResult.AsyncState; | |
Client = nodeAsyncState.Socket; | |
try | |
{ | |
Client.EndConnect(asyncResult); | |
Client.BeginReceive(buffer, 0, bufferSize, SocketFlags.None, new AsyncCallback(ReceiveData), nodeAsyncState); | |
} | |
catch (SocketException) | |
{ | |
} | |
} | |
private void ReceiveData(IAsyncResult asyncResult) | |
{ | |
var nodeAsyncState = (NodeAsyncState)asyncResult.AsyncState; | |
Socket remote = nodeAsyncState.Socket; | |
int received = remote.EndReceive(asyncResult); | |
if (nodeAsyncState.Callback != null) | |
{ | |
nodeAsyncState.Callback(buffer); | |
} | |
} | |
private void SendData(IAsyncResult asyncResult) | |
{ | |
var nodeAsyncState = (NodeAsyncState)asyncResult.AsyncState; | |
Socket remote = nodeAsyncState.Socket; | |
int sent = remote.EndSend(asyncResult); | |
remote.BeginReceive(buffer, 0, bufferSize, SocketFlags.None, new AsyncCallback(ReceiveData), nodeAsyncState); | |
} | |
public class NodeAsyncState | |
{ | |
public Socket Socket { get; set; } | |
public Action<byte[]> Callback { get; set; } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You want async!? Check out my yield hack.
https://github.com/koush/AsyncTask