SafeDispatch/SafeMobileLIB_DLL/TCPClient.cs

128 lines
3.1 KiB
C#
Raw Permalink Normal View History

2024-02-22 16:43:59 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
namespace SafeMobileLib
{
public class TCPClient
{
private bool DEBUG = true;
private TcpClient tcpClient;
private Thread listenThread;
private NetworkStream stream;
private int port;
private string ip;
public TCPClient(string ip, int port, bool DEBUG)
{
this.ip = ip;
this.port = port;
this.DEBUG = DEBUG;
}
public bool Connect()
{
bool ret = false;
try
{
tcpClient = new TcpClient(ip, port);
stream = tcpClient.GetStream();
listenThread = new Thread(new ThreadStart(HandleConnection));
listenThread.IsBackground = true;
listenThread.Start();
ret = true;
}
catch (Exception ex)
{
DebugWrite(ex.ToString());
}
return ret;
}
public void Disconnect()
{
if (listenThread != null)
{
listenThread.Abort();
}
if (stream != null)
{
stream.Close();
stream = null;
}
if (tcpClient != null && tcpClient.Connected)
{
tcpClient.Close(); tcpClient = null;
}
}
public bool Write(byte[] data, int len)
{
bool resp = false;
try
{
if (tcpClient.Connected && stream.CanWrite)
{
stream.Write(data, 0, len);
resp = true;
}
}
catch (Exception ex)
{
DebugWrite(ex.ToString());
}
return resp;
}
private void HandleConnection()
{
Byte[] data = new Byte[4096];
try
{
while (true)
{
int recv = 0;
if (stream.DataAvailable)
{
recv = stream.Read(data, 0, data.Length);
if (this.OnMessageRecv != null)
{
this.OnMessageRecv(data, recv);
}
}
Thread.Sleep(100);
}
}
catch (Exception ex)
{
DebugWrite(ex.ToString());
}
finally
{
if(stream !=null)
stream.Close();
if (tcpClient.Connected)
tcpClient.Close();
}
}
public delegate void MessageRecv(byte[] data, int recv);
public event MessageRecv OnMessageRecv;
private void DebugWrite(string txt)
{
if (DEBUG) Console.WriteLine(txt);
}
}
}