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