You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.7 KiB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace STcpHelper
{
public class STcpClient
{
private CancellationTokenSource _cts = new CancellationTokenSource();
public event EventHandler<string> MessageCallback;
public event EventHandler<Exception> ErrorCallback;
private TcpClient _client;
private NetworkStream _stream;
public async void Connect(string ip, int port)
{
try
{
_client = new TcpClient();
await _client.ConnectAsync(ip, port);
_stream = _client.GetStream();
_cts = new CancellationTokenSource();
_ = Task.Run(async () =>
{
byte[] readBuffer = new byte[1024];
while (true)
{
Thread.Sleep(50);
if (_cts.IsCancellationRequested)
break;
int bytesRead = await this._stream.ReadAsync(readBuffer);
if (bytesRead < 1)
break;
string message = Encoding.UTF8.GetString(readBuffer, 0, bytesRead);
if (this.MessageCallback != null)
this.MessageCallback(this, message);
}
}, _cts.Token);
}
catch (Exception ex)
{
WriteError(ex);
}
}
public async void SendMessage(string message)
{
try
{
byte[] sendBytes = Encoding.UTF8.GetBytes(message);
await _stream.WriteAsync(sendBytes);
}
catch (Exception ex)
{
WriteError(ex);
}
}
public void Close()
{
try
{
if (_client == null)
return;
if (_stream != null)
{
_stream.Flush();
_stream.Close();
}
_cts.Cancel();
_client.Close();
_client.Dispose();
}
catch (Exception ex)
{
WriteError(ex);
}
}
private void WriteMessage(string message)
{
if (this.MessageCallback != null)
this.MessageCallback(this, message);
}
private void WriteError(Exception ex)
{
if (this.ErrorCallback != null)
this.ErrorCallback(this, ex);
}
}
}