46 private static TcpClient
client = null;
51 private static NetworkStream
stream = null;
74 private static StringBuilder
message =
new StringBuilder();
81 public delegate
void ReadEvent(
string msg, byte[] buffer);
89 public static bool Open(
string host)
100 public static bool Open(
string host,
int port)
106 client =
new TcpClient(host, port);
108 stream = client.GetStream();
117 stream.BeginRead(buffer, 0, newLength,
new AsyncCallback(
ReadCallback), message);
119 catch (ArgumentNullException e)
121 Console.WriteLine(
"ArgumentNullException: " + e);
124 catch (SocketException e)
126 Console.WriteLine(
"SocketException: " + e.ToString());
131 Console.WriteLine(
"Unknown Exception: " + e.ToString());
143 if (stream != null) stream.Close();
144 if (client != null) client.Close();
153 if (client.Connected)
160 bytesRead = stream.EndRead(ar);
162 catch (ObjectDisposedException e)
164 Console.WriteLine(
"Connection to server dropped: " + e.ToString());
175 if (packetCounter >= 3)
181 message.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead));
184 if (receiveBuffer == null) receiveBuffer =
new byte[bytesRead];
185 else Array.Resize<byte>(ref
receiveBuffer, initialReceiveBufferIndex + bytesRead);
187 System.Buffer.BlockCopy(buffer, 0, receiveBuffer, initialReceiveBufferIndex, bytesRead);
188 initialReceiveBufferIndex = receiveBuffer.Length;
192 if (client.Available > 0)
194 newLength = client.Available;
196 else newLength = client.Available;
204 receiveBuffer = null;
205 initialReceiveBufferIndex = 0;
210 stream.BeginRead(buffer, 0, newLength,
new AsyncCallback(
ReadCallback), message);
219 public static void Write(
string mes)
221 if (client.Connected)
223 byte[] writeBuffer = Encoding.UTF8.GetBytes(mes);
225 stream.Write(writeBuffer, 0, mes.Length);
static byte [] buffer
Internal buffer used when reading data from server
static int initialReceiveBufferIndex
const int defaultPort
Default server port number
static TcpClient client
Tcp client object
static void Write(string mes)
Write a string to server
static byte [] receiveBuffer
buffer containing received message from TCP server Used to concatenate internal buffers into one ...
const int BufferMaxSize
Size of internal buffer used when reading data from server
static NetworkStream stream
Stream object used for communication
const string defaultIP
Default server name
delegate void ReadEvent(string msg, byte[] buffer)
Callback to send received message to upper level
static StringBuilder message
String containing received message from tcp server
static bool Open(string host, int port)
Open connection to server "host", with port number "port"
static bool Open(string host)
Open connection to server "host", on default port number.
Static class for TCP client
static void Close()
Close connection to server
static ReadEvent readEvent
static void ReadCallback(IAsyncResult ar)
Callback call by stream.BeginRead after reception of newLength data