David Reiss | 06a9312 | 2009-03-30 21:22:52 +0000 | [diff] [blame^] | 1 | using System; |
| 2 | using System.Collections.Generic; |
| 3 | using Thrift.Server; |
| 4 | using Thrift.Transport; |
| 5 | |
| 6 | namespace CSharpTutorial |
| 7 | { |
| 8 | public class CalculatorHandler : Calculator.Iface |
| 9 | { |
| 10 | Dictionary<int, SharedStruct> log; |
| 11 | |
| 12 | public CalculatorHandler() |
| 13 | { |
| 14 | log = new Dictionary<int, SharedStruct>(); |
| 15 | } |
| 16 | |
| 17 | public void ping() |
| 18 | { |
| 19 | Console.WriteLine("ping()"); |
| 20 | } |
| 21 | |
| 22 | public int add(int n1, int n2) |
| 23 | { |
| 24 | Console.WriteLine("add({0},{1})", n1, n2); |
| 25 | return n1 + n2; |
| 26 | } |
| 27 | |
| 28 | public int calculate(int logid, Work work) |
| 29 | { |
| 30 | Console.WriteLine("calculate({0}, [{1},{2},{3}])", logid, work.op, work.num1, work.num2); |
| 31 | int val = 0; |
| 32 | switch (work.op) |
| 33 | { |
| 34 | case Operation.ADD: |
| 35 | val = work.num1 + work.num2; |
| 36 | break; |
| 37 | |
| 38 | case Operation.SUBTRACT: |
| 39 | val = work.num1 - work.num2; |
| 40 | break; |
| 41 | |
| 42 | case Operation.MULTIPLY: |
| 43 | val = work.num1 * work.num2; |
| 44 | break; |
| 45 | |
| 46 | case Operation.DIVIDE: |
| 47 | if (work.num2 == 0) |
| 48 | { |
| 49 | InvalidOperation io = new InvalidOperation(); |
| 50 | io.what = (int)work.op; |
| 51 | io.why = "Cannot divide by 0"; |
| 52 | throw io; |
| 53 | } |
| 54 | val = work.num1 / work.num2; |
| 55 | break; |
| 56 | |
| 57 | default: |
| 58 | { |
| 59 | InvalidOperation io = new InvalidOperation(); |
| 60 | io.what = (int)work.op; |
| 61 | io.why = "Unknown operation"; |
| 62 | throw io; |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | SharedStruct entry = new SharedStruct(); |
| 67 | entry.key = logid; |
| 68 | entry.value = val.ToString(); |
| 69 | log[logid] = entry; |
| 70 | |
| 71 | return val; |
| 72 | } |
| 73 | |
| 74 | public SharedStruct getStruct(int key) |
| 75 | { |
| 76 | Console.WriteLine("getStruct({0})", key); |
| 77 | return log[key]; |
| 78 | } |
| 79 | |
| 80 | public void zip() |
| 81 | { |
| 82 | Console.WriteLine("zip()"); |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | public class CSharpServer |
| 87 | { |
| 88 | public static void Main() |
| 89 | { |
| 90 | try |
| 91 | { |
| 92 | CalculatorHandler handler = new CalculatorHandler(); |
| 93 | Calculator.Processor processor = new Calculator.Processor(handler); |
| 94 | TServerTransport serverTransport = new TServerSocket(9090); |
| 95 | TServer server = new TSimpleServer(processor, serverTransport); |
| 96 | |
| 97 | // Use this for a multithreaded server |
| 98 | // server = new TThreadPoolServer(processor, serverTransport); |
| 99 | |
| 100 | Console.WriteLine("Starting the server..."); |
| 101 | server.Serve(); |
| 102 | } |
| 103 | catch (Exception x) |
| 104 | { |
| 105 | Console.WriteLine(x.StackTrace); |
| 106 | } |
| 107 | Console.WriteLine("done."); |
| 108 | } |
| 109 | } |
| 110 | } |