blob: c790fce274c685f0019d4ae756b3363decbec920 [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;
13using System.Collections.Generic;
14using System.Text;
15using System.Net.Sockets;
16
17namespace 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
David Reiss63191332009-01-06 19:49:22 +000072 public string Host
73 {
74 get
75 {
76 return host;
77 }
78 }
79
80 public int Port
81 {
82 get
83 {
84 return port;
85 }
86 }
87
David Reiss7f42bcf2008-01-11 20:59:12 +000088 public override bool IsOpen
89 {
90 get
91 {
92 if (client == null)
93 {
94 return false;
95 }
96
97 return client.Connected;
98 }
99 }
100
101 public override void Open()
102 {
103 if (IsOpen)
104 {
105 throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen, "Socket already connected");
106 }
107
108 if (String.IsNullOrEmpty(host))
109 {
110 throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open null host");
111 }
112
113 if (port <= 0)
114 {
115 throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open without port");
116 }
117
118 if (client == null)
119 {
120 InitSocket();
121 }
122
123 client.Connect(host, port);
124 inputStream = client.GetStream();
125 outputStream = client.GetStream();
126 }
127
128 public override void Close()
129 {
130 base.Close();
131 if (client != null)
132 {
133 client.Close();
134 client = null;
135 }
136 }
137 }
138}