David Reiss | 7f42bcf | 2008-01-11 20:59:12 +0000 | [diff] [blame^] | 1 | // |
| 2 | // TSocket.cs |
| 3 | // |
| 4 | // Begin: Aug 19, 2007 |
| 5 | // Authors: |
| 6 | // Todd Berman <tberman@imeem.com> |
| 7 | // |
| 8 | // Copyright (C) 2007 imeem, inc. <http://www.imeem.com> |
| 9 | // All rights reserved. |
| 10 | // |
| 11 | |
| 12 | using System; |
| 13 | using System.Collections.Generic; |
| 14 | using System.Text; |
| 15 | using System.Net.Sockets; |
| 16 | |
| 17 | namespace Thrift.Transport |
| 18 | { |
| 19 | public class TSocket : TStreamTransport |
| 20 | { |
| 21 | private TcpClient client = null; |
| 22 | private string host = null; |
| 23 | private int port = 0; |
| 24 | private int timeout = 0; |
| 25 | |
| 26 | public TSocket(TcpClient client) |
| 27 | { |
| 28 | this.client = client; |
| 29 | |
| 30 | if (IsOpen) |
| 31 | { |
| 32 | inputStream = client.GetStream(); |
| 33 | outputStream = client.GetStream(); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | public TSocket(string host, int port) : this(host, port, 0) |
| 38 | { |
| 39 | } |
| 40 | |
| 41 | public TSocket(string host, int port, int timeout) |
| 42 | { |
| 43 | this.host = host; |
| 44 | this.port = port; |
| 45 | this.timeout = timeout; |
| 46 | |
| 47 | InitSocket(); |
| 48 | } |
| 49 | |
| 50 | private void InitSocket() |
| 51 | { |
| 52 | client = new TcpClient(); |
| 53 | client.ReceiveTimeout = client.SendTimeout = timeout; |
| 54 | } |
| 55 | |
| 56 | public int Timeout |
| 57 | { |
| 58 | set |
| 59 | { |
| 60 | client.ReceiveTimeout = client.SendTimeout = timeout = value; |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | public TcpClient TcpClient |
| 65 | { |
| 66 | get |
| 67 | { |
| 68 | return client; |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | public override bool IsOpen |
| 73 | { |
| 74 | get |
| 75 | { |
| 76 | if (client == null) |
| 77 | { |
| 78 | return false; |
| 79 | } |
| 80 | |
| 81 | return client.Connected; |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | public override void Open() |
| 86 | { |
| 87 | if (IsOpen) |
| 88 | { |
| 89 | throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen, "Socket already connected"); |
| 90 | } |
| 91 | |
| 92 | if (String.IsNullOrEmpty(host)) |
| 93 | { |
| 94 | throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open null host"); |
| 95 | } |
| 96 | |
| 97 | if (port <= 0) |
| 98 | { |
| 99 | throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open without port"); |
| 100 | } |
| 101 | |
| 102 | if (client == null) |
| 103 | { |
| 104 | InitSocket(); |
| 105 | } |
| 106 | |
| 107 | client.Connect(host, port); |
| 108 | inputStream = client.GetStream(); |
| 109 | outputStream = client.GetStream(); |
| 110 | } |
| 111 | |
| 112 | public override void Close() |
| 113 | { |
| 114 | base.Close(); |
| 115 | if (client != null) |
| 116 | { |
| 117 | client.Close(); |
| 118 | client = null; |
| 119 | } |
| 120 | } |
| 121 | } |
| 122 | } |