Skip to content

Instantly share code, notes, and snippets.

@dragan
Created March 17, 2011 03:37
Show Gist options
  • Save dragan/873786 to your computer and use it in GitHub Desktop.
Save dragan/873786 to your computer and use it in GitHub Desktop.
A few changes to Node to show async for Jason
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; }
}
}
}
@koush
Copy link

koush commented Mar 17, 2011

You want async!? Check out my yield hack.

https://github.com/koush/AsyncTask

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment