C# Server - TcpClient.Client.Receive - Is there a way to cancel it

  • Thread starter Thread starter Markus Freitag
  • Start date Start date
M

Markus Freitag

Guest
Hello,
My goal is to start a server with a start button, with an end button immediately stop.
How do I achieve this?
I have a server that works well.
If I press Abort, set the Cancel flag, it will hang there. This code row.
sizeReceive = tcpClient.Client.Receive(buffer, 0, buffer.Length, SocketFlags.None);
OK, is a loop and wait for receiving data.

Although I seem to be disconnected, I have to send something.
How can I solve this better? I'm looking for a easy solution.
Best regards Markus

//My forgiven attempts
//Variant 01

private XElement HandleConnection(TcpClient tcpClient, CancellationToken token)
{
string clientInfo = tcpClient.Client.RemoteEndPoint.ToString();

IPEndPoint RemAddr = (IPEndPoint)tcpClient.Client.RemoteEndPoint;
IPEndPoint LocAddr = (IPEndPoint)tcpClient.Client.LocalEndPoint;

EvHaReceived?.Invoke(this, new ServerEventArgs() { MessageType = MessageTypes.MessageReceived, Message = $"Server:Connection established on port {Port}" });

try
{
tcpClient.LingerState.Enabled = false;
LogMessage(string.Format("Got connection request from {0}", clientInfo));

var buffer = new byte[10000];
int sizeReceive = -1;
string receiveBuffer = string.Empty;

while (sizeReceive != 0 && !token.IsCancellationRequested)
{
Array.Clear(buffer, 0, buffer.Length);
try
{
sizeReceive = tcpClient.Client.Receive(buffer, 0, buffer.Length, SocketFlags.None);



//Variant 02

private Socket listener;
private byte[] buffer = new byte[8192];

public void StartListening()
{
listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(new IPEndPoint(IPAddress.Any, 21));
listener.Listen(20);
listener.BeginAccept(OnSocketAccepted, null);
}

public void StoppListening()
{
listener.Close(); // not working
}

private void OnSocketAccepted(IAsyncResult result)
{
try
{
Socket client = listener.EndAccept(result);


client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, OnDataReceived, client); // Start receiving data from this client.

// Start a new async accept operation to accept incoming connections from other clients.
// listener.BeginAccept(OnSocketAccepted, null);
}
catch (SocketException ex)
{
Log.Error($"Error {ex.Message}");
}
catch (Exception ex1)
{
Log.Error($"Error {ex1.Message}");
}
}

private void OnDataReceived(IAsyncResult result)
{
Socket client = result.AsyncState as Socket;
int received = client.EndReceive(result);

byte[] buf1 = null;
buf1 = Encoding.Default.GetBytes("<TEST>tttttt</TEST>");
client.Send(buf1);

// Start a new async receive on the client to receive more data.
client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, OnDataReceived, client);
}

Continue reading...
 

Similar threads

P
Replies
0
Views
176
Policy standard local admin account with Active Di
P
Back
Top