summaryrefslogtreecommitdiff
path: root/contrib/zeromq/csharp/TZmqServer.cs
blob: 535c623d078596133cc67627b541dd9db916b3ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System;
using Thrift;
using Thrift.Server;
using Thrift.Transport;
using Thrift.Protocol;
using ZMQ;
using System.IO;

using System.Collections.Generic;

namespace ZmqServer
{
	public class TZmqServer
	{
		Socket _socket ;
		TProcessor _processor;
		
		void debug (string msg)
		{
			//Uncomment to enable debug
//			Console.WriteLine (msg);
		}

		public TZmqServer (TProcessor processor, Context ctx, String endpoint, SocketType sockType)
		{
			new TSimpleServer (processor,null);
			_socket = ctx.Socket (sockType);
			_socket.Bind (endpoint);
			_processor = processor;
		}

		public void ServeOne ()
		{
			debug ("Server_ServeOne");
			Byte[] msg = _socket.Recv ();
			MemoryStream istream = new MemoryStream (msg);
			MemoryStream ostream = new MemoryStream ();
			TProtocol tProtocol = new TBinaryProtocol (new TStreamTransport (istream, ostream));
			_processor.Process (tProtocol, tProtocol);

			if (ostream.Length != 0) {
				byte[] newBuf = new byte[ostream.Length];
				Array.Copy (ostream.GetBuffer (), newBuf, ostream.Length);
				debug (string.Format ("Server_ServeOne sending {0}b", ostream.Length));
				_socket.Send (newBuf);
			}
		}

		public void Serve ()
		{
			while (true)
				ServeOne ();
		}
	}
}