123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.IO;
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
-
- namespace Combot
- {
- class TCPInterface
- {
- internal event Action<TCPError> TCPErrorEvent;
- internal event Action<int> TCPConnectionEvent;
-
- private IPEndPoint _serverIP = null;
- private int _readTimeout = 250;
- private Socket _tcpClient;
- private NetworkStream _tcpStream;
- private int _allowedFailedCount;
- private int _currentFailedCount;
-
- internal TCPInterface()
- {
- }
-
- internal bool Connect(IPAddress IP, int port, int readTimeout, int allowedFailedCount = 0)
- {
- _serverIP = new IPEndPoint(IP, port);
- _readTimeout = readTimeout;
- _allowedFailedCount = allowedFailedCount;
- _currentFailedCount = 0;
-
- try
- {
- _tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- _tcpClient.Connect(_serverIP);
- _tcpClient.ReceiveTimeout = _readTimeout;
-
- _tcpStream = new NetworkStream(_tcpClient);
- return true;
- }
- catch
- {
- if (TCPErrorEvent != null)
- {
- TCPError error = new TCPError();
- error.Message = string.Format("Unable to connect to {0} on port {1}", _serverIP.Address, _serverIP.Port);
- TCPErrorEvent(error);
- }
- }
- return false;
- }
-
- internal void Disconnect()
- {
- if (_tcpStream != null)
- {
- _tcpStream.Close();
- }
- if (_tcpClient != null)
- {
- _tcpClient.Close();
- }
- }
-
- internal void Write(string data)
- {
- if (_tcpStream.CanWrite)
- {
- byte[] message = System.Text.Encoding.UTF8.GetBytes(data + Environment.NewLine);
- _tcpStream.Write(message, 0, message.Length);
- }
- }
-
- internal string Read()
- {
- try
- {
- if (_tcpStream.CanRead)
- {
- byte[] readBytes = new byte[100000];
- _tcpStream.Read(readBytes, 0, readBytes.Length);
- string result = Encoding.UTF8.GetString(readBytes, 0, readBytes.Length);
- // Reset Failed Counter
- _currentFailedCount = 0;
- return result.TrimEnd('\0');
- }
- }
- catch (IOException)
- {
- _currentFailedCount++;
- if (TCPErrorEvent != null && _tcpStream.CanRead)
- {
- TCPError error = new TCPError();
- error.Message = string.Format("Read Timeout, No Response from Server in {0}ms", _readTimeout);
- TCPErrorEvent(error);
- }
- }
- catch (Exception ex)
- {
- _currentFailedCount++;
- if (TCPErrorEvent != null)
- {
- TCPError error = new TCPError();
- error.Message = ex.Message;
- TCPErrorEvent(error);
- }
- }
-
- if (_currentFailedCount > _allowedFailedCount)
- {
- if (TCPConnectionEvent != null)
- {
- TCPConnectionEvent(_currentFailedCount);
- }
- Disconnect();
- _currentFailedCount = 0;
- }
- return null;
- }
- }
- }
|