Skip to content

Commit

Permalink
Client-server communication start
Browse files Browse the repository at this point in the history
  • Loading branch information
leboeuf committed Apr 23, 2016
1 parent b77e412 commit c212999
Show file tree
Hide file tree
Showing 8 changed files with 325 additions and 7 deletions.
6 changes: 6 additions & 0 deletions OrderBook.Client/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
60 changes: 60 additions & 0 deletions OrderBook.Client/OrderBook.Client.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{9B0918FE-F67A-4385-B2DB-BCD39420468A}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>OrderBook.Client</RootNamespace>
<AssemblyName>OrderBook.Client</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
51 changes: 51 additions & 0 deletions OrderBook.Client/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace OrderBook.Client
{
class Program
{
private const int ORDERBOOK_ENDPOINTSERVER_PORT = 32000;

private static void Main(String[] args)
{
System.Threading.Thread.Sleep(1000); // DEBUG: wait for server to be ready because server and client start at the same time when debugging

byte[] data = new byte[512];

var iphostInfo = Dns.GetHostEntry(Dns.GetHostName());
var ipAddress = iphostInfo.AddressList[0];
var ipEndpoint = new IPEndPoint(ipAddress, ORDERBOOK_ENDPOINTSERVER_PORT);
var client = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

try
{
client.Connect(ipEndpoint);

Console.WriteLine("Socket created to {0}", client.RemoteEndPoint.ToString());
Console.WriteLine("Press any key to send an order to the server.");

byte[] sendmsg = Encoding.ASCII.GetBytes("{\"o\": \"BUY\", \"q\": 100, \"s\": \"TEST\", \"p\": 10}\n");

int n = client.Send(sendmsg);

int bytesRead = client.Receive(data);

Console.WriteLine(Encoding.ASCII.GetString(data, 0, bytesRead));
client.Shutdown(SocketShutdown.Both);
client.Close();

}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}

Console.WriteLine("Transmission end.");
Console.ReadKey();

}
}
}
36 changes: 36 additions & 0 deletions OrderBook.Client/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("OrderBook.Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OrderBook.Client")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9b0918fe-f67a-4385-b2db-bcd39420468a")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
152 changes: 152 additions & 0 deletions OrderBook.EndpointServer/AsynchronousSocketListener.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace OrderBook.EndpointServer
{
// State object for reading client data asynchronously
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 512;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}

/// <remarks>
/// Adapted from https://msdn.microsoft.com/en-us/library/fx6588te(v=vs.110).aspx
/// </remarks>
public class AsynchronousSocketListener
{
// Thread signal.
public ManualResetEvent allDone = new ManualResetEvent(false);
private readonly int _listenPort;

public AsynchronousSocketListener(int listenPort)
{
_listenPort = listenPort;
}

public void StartListening()
{
var ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
var ipAddress = ipHostInfo.AddressList[0];
var localEndPoint = new IPEndPoint(ipAddress, _listenPort);
var listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);


// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(100); // backlog size may be improved with load testing metrics http://tangentsoft.net/wskfaq/advanced.html#backlog

while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();

// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);

// Wait until a connection is made before continuing.
allDone.WaitOne();
}

}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}

Console.WriteLine("\nPress ENTER to continue...");
Console.Read();

}

public void AcceptCallback(IAsyncResult asyncResult)
{
// Signal the main thread to continue.
allDone.Set();

// Get the socket that handles the client request.
Socket listener = (Socket)asyncResult.AsyncState;
Socket handler = listener.EndAccept(asyncResult);

// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}

public void ReadCallback(IAsyncResult asyncResult)
{
String content = String.Empty;

// Retrieve the state object and the handler socket from the asynchronous state object.
StateObject state = (StateObject)asyncResult.AsyncState;
Socket handler = state.workSocket;

// Read data from the client socket.
int bytesRead = handler.EndReceive(asyncResult);

if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

// Check for end-of-line tag. If it is not there, read more data.
content = state.sb.ToString();
if (content.IndexOf("\n") > -1)
{
// All the data has been read from the client. Display it on the console.
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
// Echo the data back to the client.
Send(handler, content);
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
}
}

private void Send(Socket handler, string data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);

// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
}

private void SendCallback(IAsyncResult asyncResult)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket)asyncResult.AsyncState;

// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(asyncResult);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);

handler.Shutdown(SocketShutdown.Both);
handler.Close();

}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
1 change: 1 addition & 0 deletions OrderBook.EndpointServer/OrderBook.EndpointServer.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AsynchronousSocketListener.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
Expand Down
20 changes: 13 additions & 7 deletions OrderBook.EndpointServer/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using OrderBook.Core.Model;
using System;
using System.Collections.Generic;
using System.Messaging;

namespace OrderBook.EndpointServer
Expand All @@ -12,17 +11,17 @@ class Program
private const string MESSAGE_QUEUE_TX_NAME = @".\Private$\OrderBookServer_OrdersQueue";
private static MessageQueue _rxMessageQueue;
private static MessageQueue _txMessageQueue;
private const int LISTEN_PORT = 32000;

static void Main(string[] args)
{
InitializeMessageQueues();
//StartListeningToProcessedOrders();
StartListeningToClients();
}

var order1 = new Core.Model.Order("TEST", Core.Model.Enums.OrderSide.Sell, 100, 10);
var order2 = new Core.Model.Order("TEST", Core.Model.Enums.OrderSide.Buy, 100, 10);

_txMessageQueue.Send(order1);
_txMessageQueue.Send(order2);

private static void StartListeningToProcessedOrders()
{
while (true)
{
var message = _rxMessageQueue.Receive();
Expand All @@ -31,6 +30,13 @@ static void Main(string[] args)
}
}

private static void StartListeningToClients()
{
var listener = new AsynchronousSocketListener(LISTEN_PORT);
// TODO: bind events
listener.StartListening();
}

private static void InitializeMessageQueues()
{
CreateOrOpenQueue(ref _rxMessageQueue, MESSAGE_QUEUE_RX_NAME);
Expand Down
6 changes: 6 additions & 0 deletions OrderBook.sln
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OrderBook.Core", "OrderBook
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OrderBook.EndpointServer", "OrderBook.EndpointServer\OrderBook.EndpointServer.csproj", "{2B7DAF0D-4400-420E-A5A5-8296F91701EE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OrderBook.Client", "OrderBook.Client\OrderBook.Client.csproj", "{9B0918FE-F67A-4385-B2DB-BCD39420468A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -27,6 +29,10 @@ Global
{2B7DAF0D-4400-420E-A5A5-8296F91701EE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2B7DAF0D-4400-420E-A5A5-8296F91701EE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2B7DAF0D-4400-420E-A5A5-8296F91701EE}.Release|Any CPU.Build.0 = Release|Any CPU
{9B0918FE-F67A-4385-B2DB-BCD39420468A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9B0918FE-F67A-4385-B2DB-BCD39420468A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9B0918FE-F67A-4385-B2DB-BCD39420468A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9B0918FE-F67A-4385-B2DB-BCD39420468A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down

0 comments on commit c212999

Please sign in to comment.