Unable to close loop running in thread at application close. tcp/ip - c#

I'm working on one TCP client server application and running the TCP server in loop but when I close the application loop continuously runs and send data to device.
Here is the scenario:
TCP server runs and listen to client(handheld device) once the device connected as long as there is no data receive from the device server needs to send empty data continuously to device.
Code:
private TCPMainListener tcpListener;
private Thread listenThread;
private TcpClient client;
public bool checkFormIsClose { get; set; }
List<Thread> listenThreads;
public void startTcpServer()
{
this.tcpListener = new TCPMainListener(IPAddress.Any, Convert.ToInt32(tcpport));
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
listenThreads.Add(listenThread);
}
private void ListenForClients()
{
try
{
this.tcpListener.Start();
}
catch (Exception ex)
{
throw ex;
}
while (!checkFormIsClose)
{
try
{
//blocks until a client has connected to the server
client = (TcpClient)this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
catch
{
break;
}
}
}
Client Handle:
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[100];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 40);
#region Write to client until message receive
int timeout = 0;
//send empty byte to device until bytesRead != 0
do
{
Thread.Sleep(50);
timeout++;
if (timeout == 10)
{
byte[] b = new byte[] { 0x00 };
tcpClient.GetStream().Write(b, 0, b.Length);
timeout = 1;
}
} while (bytesRead == 0);
#endregion
if (bytesRead != 0)
{
//message has successfully been received
if (BitConverter.ToString(message).Replace("-", "").StartsWith("FF"))
{
CardProcessing(message);
}
}
}
catch
{
//a socket error has occured
break;
}
}
tcpClient.Close();
}
Now here is my form closing code:
and they are not doing anything at all
private void TCPMAINSERVER_FormClosing(object sender, FormClosingEventArgs e)
{
foreach (Thread thread in listenThreads)
{
checkFormIsClose = true;
System.Threading.Tasks.Task.Factory.StartNew(() =>
{
checkFormIsClose = true;
tcpListener.Stop();
Process.GetCurrentProcess().Close();
GC.SuppressFinalize(thread);
thread.Join();
thread.Interrupt();
});
}
}
private void TCPMAINSERVER_FormClosed(object sender, FormClosedEventArgs e)
{
foreach (Thread thread in listenThreads)
{
checkFormIsClose = false;
System.Threading.Tasks.Task.Factory.StartNew(() =>
{
tcpListener.Stop();
Process.GetCurrentProcess().Close();
GC.SuppressFinalize(thread);
thread.Join();
thread.Interrupt();
});
}
}

Related

Unable to read data from tcp server

I have created a simple C# client application. Once it connects to the server it should read the messages sent from the server. It also has the ability to send messages to server too. However I am unable to figure out to correct way to read the data.
I am spawning a thread once it connects to the server. The thread runs in infinite loop and have two interfaces each for reading and writing. Connect() method is called from a ButtonClick event.
My code snippet is as below:
namespace WpfApp1
{
public class TCPClientClass
{
private StreamWriter SwSender;
NetworkStream Sender;
NetworkStream Receiver;
//private StreamReader SrReciever;
private Thread thrMessaging;
TcpClient tcp;
bool connected = false;
public bool Connected { get { return connected; } set { connected = value; } }
//public bool Connect(IPAddress IP, int nPortNo)
public async Task Connect(IPAddress IP, int nPortNo)
{
tcp = new TcpClient();
try
{
//tcp.Connect(strIPAddress.Parse("192.168.137.1"), 2000);
// tcp.Connect(IP , nPortNo);
await tcp.ConnectAsync(IP, nPortNo);
thrMessaging = new Thread(new ThreadStart(ThreadFunction));
thrMessaging.Start();
Connected = true;
}
catch
{
MessageBox.Show("Unable to connect to server");
//return false;
}
//return true;
}
public void Disconnect()
{
Sender?.Close();
Receiver?.Close();
tcp?.Close();
//tcp?.Client.Disconnect(false);
thrMessaging.Abort();
Connected = false;
}
private void ThreadFunction()
{
while (thrMessaging.IsAlive)
DoTasks();
}
private void DoTasks()
{
if (Connected)
{
var a = ReadMessages();
SendMessages();
}
}
private /*void*/async Task ReadMessages()
{
byte[] data = new byte[4096];
//Int32 bytesRead = 0;
//Task<int> bytesReadTask;
String responseData = String.Empty;
Receiver = tcp.GetStream();
try
{
//bytesReadTask = Receiver.ReadAsync(data, 0, data.Length);
//responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytesReadTask.Result);
var response = await Receiver.ReadAsync(data, 0, data.Length);
MessageBox.Show("Server response was " + response);
Thread.Sleep(1000);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
private void SendMessages()
{
try
{
string strSendData = "Hello from GUI";
Byte[] data = System.Text.Encoding.ASCII.GetBytes(strSendData);
Sender = tcp.GetStream();
Sender.Write(data, 0, data.Length);
Sender.Flush();
Thread.Sleep(1000);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
}
you should change
var response = await Receiver.ReadAsync(data, 0, data.Length);
MessageBox.Show("Server response was " + response);
to
var response = await Receiver.ReadAsync(data, 0, data.Length);
string result = System.Text.Encoding.Default.GetString(data);
MessageBox.Show("Server response was " + result);
if you´re still having problems..my server Code:
public class tcpServer
{
public void method()
{
TcpListener server = new TcpListener(IPAddress.Any, 9999);
server.Start();
TcpClient client = server.AcceptTcpClient();
NetworkStream ns = client.GetStream();
byte[] hello = new byte[100];
hello = Encoding.Default.GetBytes("hello world");
while (client.Connected)
{
ns.Write(hello, 0, hello.Length);
}
}
}

Async TCPClient missing replies from server

I'm trying to implement an async TCP client that sends messages from a queue and listens to the response.
some of the server replies are lost (for example send 7 messages and get only 4 replies) and I don't understand why.
This is not a server issue, since the synchronize version I tested works just fine.
ConcurrentQueue<byte[]> msgQueue = new ConcurrentQueue<byte[]>();
public void Connect()
{
try
{
tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
Task.Factory.StartNew(() =>
{
IAsyncResult res = tcpclnt.BeginConnect(_ip, _port, null, null);
if (!res.AsyncWaitHandle.WaitOne(CONNECTION_TIMEOUT_SEC * 1000))
{
tcpclnt.Close();
throw new ApplicationException("timed out trying to connect");
}
tcpclnt.EndConnect(res);
Receive();
byte[] message = null;
while (true)
{
message = null;
msgQueue.TryDequeue(out message);
if (message != null)
{
Stream stm = tcpclnt.GetStream();
Console.WriteLine("Transmitting..... " + Thread.CurrentThread.ManagedThreadId);//for debug
stm.Write(message.ToArray(), 0, message.ToArray().Length);
Receive();
}
}
});
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
//will be called from outside
public void SendMessage(byte[] msg)
{
Console.WriteLine("SendMessage..... " + Thread.CurrentThread.ManagedThreadId);//for debug
msgQueue.Enqueue(msg);
}
private void Receive()
{
SocketError error;
byte[] buffer = new byte[MAX_BUFFER_SIZE];
tcpclnt.Client.BeginReceive(buffer, 0, MAX_BUFFER_SIZE, SocketFlags.None, out error, new AsyncCallback(ReceiveHandler), buffer);
}
private void ReceiveHandler(IAsyncResult ar)
{
System.Console.WriteLine("ReceiveHandler " + Thread.CurrentThread.ManagedThreadId); //for debug
//End current async receive
int bytesRead = tcpclnt.Client.EndReceive(ar);
byte[] resultBuffer = (byte[]) ar.AsyncState;
// do a lot of things with resultBuffer
}

How to detect the disconnected TCP connection and again connect

I have a TCP/IP client program in a Windows service written in C#. As of now everything is working fine. But I have a query that supposes my connection to the machine goes down due to any reasons say machine is out of the network or something. How will my application detect that and also tries to connect or regain the connection again?
Here is the code that I am using in my Windows service:
private ManualResetEvent _shutdownEvent = new ManualResetEvent(false);
protected override void OnStart(string[] args)
{
_thread = new Thread(DoWork);
_thread.Start();
System.Timers.Timer _timer = new System.Timers.Timer(60 * 1000); // every 60 seconds
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
_timer.Start(); // <- important
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (client.Connected)
{
//Do nothing
}
else {
//close the thread and again start.
try
{
using (StreamWriter streamWriter = File.AppendText(textfileSaveLocation))
{
streamWriter.WriteLine("Disconnected!!!!");
}
}
catch (Exception Ex)
{
Ex.Message.ToString();
}
_shutdownEvent.Set();
_thread.Start();
}
}
private void DoWork()
{
while (!_shutdownEvent.WaitOne(0))
{
TcpClient client = new TcpClient();
string data= "";
fileSaveLocation = location;
try
{
client.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
}
catch (Exception ex)
{
// Log the error here.
client.Close();
continue;
}
try
{
using (NetworkStream stream = client.GetStream())
{
byte[] notify = Encoding.ASCII.GetBytes("Hello");
stream.Write(notify, 0, notify.Length);
byte[] data = new byte[1024];
while (!_shutdownEvent.WaitOne(0))
{
int numBytesRead = stream.Read(data, 0, data.Length);
if (numBytesRead > 0)
{
data= Encoding.ASCII.GetString(data, 0, numBytesRead);
}
}
}
}
catch (Exception ex)
{
// Log the error here.
client.Close();
}
}
}
protected override void OnStop()
{
_shutdownEvent.Set(); // trigger the thread to stop
_thread.Join(); // wait for thread to stop
}
Please help me. Any suggestions will be helpful. Thanks ..
TcpClient does not get notified when the connection is closed or disconnected. You can check manually if TcpClient is connected in every certain period like -
if(tcpClient.Connected)
{
//code
}
else
{
//renew connection
}
Or, you have to handle the Exception in Catch block and code as required.

c# SocketAsyncEventArgs blocking code inside ReceiveAsync handler

I have the the following two scenarios that I am testing and one works but the other does not.
I have socket server and socket client application running on two different machines
both the scenarios are using the socketasynceventargs
Scenario 1 (Works)
create 40k socket clients in a loop, wait for all connections to be established and then all clients send messages to the server at the same time and receive response from the server 10 times(i.e. send/receive happens 10 times).
Scenario 2 (Does not work. I get a lot of connection refusal errors)
create 40k socket clients in a loop and send/receive the same 10 messages to the server as soon as each client is connected instead of waiting for the 40k connections to be established.
I cant figure out why my second scenario would fail. i understand that in scenario 1 the server is not doing much until all the 40k connections are made. but it is able to communicate with all the clients at the same time. any ideas??
Thank you for you patience.
here is the socket server code
public class SocketServer
{
private static System.Timers.Timer MonitorTimer = new System.Timers.Timer();
public static SocketServerMonitor socket_monitor = new SocketServerMonitor();
private int m_numConnections;
private int m_receiveBufferSize;
public static BufferManager m_bufferManager;
Socket listenSocket;
public static SocketAsyncEventArgsPool m_readWritePool;
public static int m_numConnectedSockets;
private int cnt = 0;
public static int Closecalled=0;
public SocketServer(int numConnections, int receiveBufferSize)
{
m_numConnectedSockets = 0;
m_numConnections = numConnections;
m_receiveBufferSize = receiveBufferSize;
m_bufferManager = new BufferManager(receiveBufferSize * numConnections ,
receiveBufferSize);
m_readWritePool = new SocketAsyncEventArgsPool(numConnections);
}
public void Init()
{
MonitorTimer.Interval = 30000;
MonitorTimer.Start();
MonitorTimer.Elapsed += new System.Timers.ElapsedEventHandler(socket_monitor.Log);
m_bufferManager.InitBuffer();
SocketAsyncEventArgs readWriteEventArg;
for (int i = 0; i < m_numConnections; i++)
{
readWriteEventArg = new SocketAsyncEventArgs();
m_readWritePool.Push(readWriteEventArg);
}
}
public void Start(IPEndPoint localEndPoint)
{
listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listenSocket.Bind(localEndPoint);
listenSocket.Listen(1000);
StartAccept(null);
}
public void Stop()
{
if (listenSocket == null)
return;
listenSocket.Close();
listenSocket = null;
Thread.Sleep(15000);
}
private void StartAccept(SocketAsyncEventArgs acceptEventArg)
{
if (acceptEventArg == null)
{
acceptEventArg = new SocketAsyncEventArgs();
acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(AcceptEventArg_Completed);
}
else
{
// socket must be cleared since the context object is being reused
acceptEventArg.AcceptSocket = null;
}
try
{
bool willRaiseEvent = listenSocket.AcceptAsync(acceptEventArg);
if (!willRaiseEvent)
{
ProcessAccept(acceptEventArg);
}
}
catch (Exception e)
{
}
}
void AcceptEventArg_Completed(object sender, SocketAsyncEventArgs e)
{
ProcessAccept(e);
}
private void ProcessAccept(SocketAsyncEventArgs e)
{
Interlocked.Increment(ref m_numConnectedSockets);
socket_monitor.IncSocketsConnected();
SocketAsyncEventArgs readEventArgs = m_readWritePool.Pop();
m_bufferManager.SetBuffer(readEventArgs);
readEventArgs.UserToken = new AsyncUserToken { id = cnt++, StarTime = DateTime.Now };
readEventArgs.AcceptSocket = e.AcceptSocket;
SocketHandler handler=new SocketHandler(readEventArgs);
StartAccept(e);
}
}
class SocketHandler
{
private SocketAsyncEventArgs _socketEventArgs;
public SocketHandler(SocketAsyncEventArgs socketAsyncEventArgs)
{
_socketEventArgs = socketAsyncEventArgs;
_socketEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
StartReceive(_socketEventArgs);
}
private void StartReceive(SocketAsyncEventArgs receiveSendEventArgs)
{
bool willRaiseEvent = receiveSendEventArgs.AcceptSocket.ReceiveAsync(receiveSendEventArgs);
if (!willRaiseEvent)
{
ProcessReceive(receiveSendEventArgs);
}
}
private void ProcessReceive(SocketAsyncEventArgs e)
{
// check if the remote host closed the connection
AsyncUserToken token = (AsyncUserToken)e.UserToken;
//token.StarTime = DateTime.Now;
if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
{
// process the data here
//reply to client
byte[] AckData1 = BitConverter.GetBytes(1);
SendData(AckData1, 0, AckData1.Length, e);
StartReceive(e);
}
else
{
CloseClientSocket(e);
}
}
private void IO_Completed(object sender, SocketAsyncEventArgs e)
{
// determine which type of operation just completed and call the associated handler
switch (e.LastOperation)
{
case SocketAsyncOperation.Receive:
ProcessReceive(e);
break;
case SocketAsyncOperation.Send:
ProcessSend(e);
break;
default:
throw new ArgumentException("The last operation completed on the socket was not a receive or send");
}
}
private void CloseClientSocket(SocketAsyncEventArgs e)
{
AsyncUserToken token = e.UserToken as AsyncUserToken;
// close the socket associated with the client
try
{
e.AcceptSocket.Shutdown(SocketShutdown.Send);
}
catch (Exception ex)
{
}
e.AcceptSocket.Close();
Interlocked.Decrement(ref SocketServer.m_numConnectedSockets);
SocketServer.socket_monitor.DecSocketsConnected();
SocketServer.m_bufferManager.FreeBuffer(e);
e.Completed -= new EventHandler<SocketAsyncEventArgs>(IO_Completed);
SocketServer.m_readWritePool.Push(e);
}
public void SendData(Byte[] data, Int32 offset, Int32 count, SocketAsyncEventArgs args)
{
try
{
Socket socket = args.AcceptSocket;
if (socket.Connected)
{
var i = socket.Send(data, offset, count, SocketFlags.None);
}
}
catch (Exception Ex)
{
}
}
}
here is the client code that throws the error in the connectcallback method
// State object for receiving data from remote device.
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
public int count = 0;
}
public class AsynchronousClient
{
// The port number for the remote device.
private const int port = 11000;
private static int closecalled = 0;
private static bool wait = true;
// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone =
new ManualResetEvent(false);
private static ManualResetEvent sendDone =
new ManualResetEvent(false);
private static ManualResetEvent receiveDone =
new ManualResetEvent(false);
// The response from the remote device.
private static String response = String.Empty;
private static void StartClient(Socket client, IPEndPoint remoteEP)
{
// Connect to a remote device.
try
{
// Connect to the remote endpoint.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), new StateObject { workSocket = client });
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
StateObject state = (StateObject)ar.AsyncState;
var client = state.workSocket;
// Complete the connection.
client.EndConnect(ar);
var data = "AA5500C08308353816050322462F01020102191552E7D3FA52E7D3FB1FF85BF1FE9F201000004AB80000000500060800001EFFB72F0D00002973620000800000FFFFFFFF00009D6D00003278002EE16D0000018500000000000000000000003A0000000100000000828C80661FF8B436FE9EA9FC000000120000000700000000000000000000000400000000000000000000000000000000000000000000281E0000327800000000000000000000000000AF967D00000AEA000000000000000000000000";
Send(state, data);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void Receive(StateObject state)
{
try
{
Socket client = state.workSocket;
// Begin receiving the data from the remote device.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
//if (wait)
//{
// connectDone.WaitOne();
//}
if (bytesRead > 0)
{
state.count = state.count + 1;
byte[] b = new byte[bytesRead];
Array.Copy(state.buffer, b, 1);
if (b[0] == 1)
{
if (state.count < 10)
{
var data = "AA5500C08308353816050322462F01020102191552E7D3FA52E7D3FB1FF85BF1FE9F201000004AB80000000500060800001EFFB72F0D00002973620000800000FFFFFFFF00009D6D00003278002EE16D0000018500000000000000000000003A0000000100000000828C80661FF8B436FE9EA9FC000000120000000700000000000000000000000400000000000000000000000000000000000000000000281E0000327800000000000000000000000000AF967D00000AEA000000000000000000000000";
Send(state, data);
}
else
{
Interlocked.Increment(ref closecalled);
Console.WriteLine("closecalled:-" + closecalled + " at " + DateTime.Now);
client.Close();
}
}
else
{
// Get the rest of the data.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
}
else
{
client.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void Send(StateObject state, String data)
{
try
{
Socket client = state.workSocket;
var hexlen = data.Length;
byte[] byteData = new byte[hexlen / 2];
int[] hexarray = new int[hexlen / 2];
int i = 0;
int k = 0;
//create the byte array
while (i < data.Length / 2)
{
string first = data[i].ToString();
i++;
string second = data[i].ToString();
string x = first + second;
byteData[k] = (byte)Convert.ToInt32(x, 16);
i++;
k++;
}
// Begin sending the data to the remote device.
client.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
Receive(state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
Start();
Console.ReadLine();
return 0;
}
private static void Start()
{
IPAddress ipaddress = IPAddress.Parse("10.20.2.152");
IPEndPoint remoteEP = new IPEndPoint(ipaddress, port);
for (int i = 0; i < 40000; i++)
{
Thread.Sleep(1);
// Create a TCP/IP socket.
try
{
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
StartClient(client, remoteEP);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
if (i == 39999)
{
Console.WriteLine("made all conns at " + DateTime.Now);
}
}
}
}
I would use a linear queue to accept incoming connections. Something like this:
public async Task Accept40KClients()
{
for (int i = 0; i < 40000; i++)
{
// Await this here -------v
bool willRaiseEvent = await listenSocket.AcceptAsync(acceptEventArg);
if (!willRaiseEvent)
{
ProcessAccept(acceptEventArg);
}
}
}
If that's not fast enough, maybe you can do 10 waits at a time, but I think this is good enough... I might be wrong on this though.

Sockets.Connected is always true?

I have a small file transfer application using WCF service, that send files and folders over tcp sockets.My problem that when i cancel the transfer operation (backgroundworker) from the client, the server still freezed on client.Receive, It supposes to give me this exception: An existing connection was forcibly closed by the remote host ,but it doesn't,despite on the client side the listener.Connected becomes false and socket.Connected becomes false
I need to get this exception and handle it so i can close the stream and the socket and be ready to receive another task!
Client Side:
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
List<Job> Jobs = (List<Job>)e.Argument;
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);
listener.Bind(endpoint);
listener.Listen(1);
client.ConnectToClient((IPEndPoint)listener.LocalEndPoint);
Socket socket = listener.Accept();
foreach (Job job in Jobs)
{
if (job.IsFile)
{
if (job.IsSend)
{ SendFile(socket, job, e); } //here i send a single file.
// else
// { ReceiveFile(socket, job, e); }
}
// else
// {
// if (job.IsSend)
// { SendDir(socket, job, e); }
// else
// { ReceiveDir(socket, job, e); }
// }
if (worker.CancellationPending)
{
e.Cancel = true;
socket.Dispose();
listener.Dispose();
Console.WriteLine(socket.Connected + " " + listener.Connected);
//it prints "FALSE FALSE"
return;
}
}
}
}
private void SendFile(Socket socket, Job job, DoWorkEventArgs e)
{
UpdateInfo(job.Name, job.Icon); //update GUI with file icon and name.
client.ReceiveFile((_File)job.Argument, bufferSize); //tell the client to start receiving
SendX(socket, ((_File)job.Argument).Path, e); //start sending..
}
private void SendX(Socket socket, string filePath, DoWorkEventArgs e)
{
using (Stream stream = File.OpenRead(filePath))
{
byte[] buffer = new byte[bufferSize];
long sum = 0;
int count = 0;
while (sum < stream.Length)
{
if (worker.CancellationPending)
{
e.Cancel = true;
return;
}
count = stream.Read(buffer, 0, buffer.Length);
socket.Send(buffer, 0, count, SocketFlags.None);
sum += count;
SumAll += count;
worker.ReportProgress((int)((sum * 100) / stream.Length));
}
}
}
Server Side:
public void ConnectToClient(IPEndPoint endpoint)
{
if (client == null)
{
Thread th = new Thread(unused => ConnectTh(endpoint));
th.Start();
}
}
private void ConnectTh(IPEndPoint endpoint)
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(IPAddress.Parse("127.0.0.1"), endpoint.Port);
}
public void ReceiveFile(_File file, int bufferSize)
{
System.Threading.Thread th = new System.Threading.Thread(unused => ReceiveX(client, file.Name, file.Size, bufferSize));
th.Start();
}
private void ReceiveX(Socket client, string destPath, long size, int bufferSize)
{
try
{
using (Stream stream = File.Create(destPath))
{
byte[] buffer = new byte[bufferSize];
long sum = 0;
int count = 0;
while (sum < size)
{
int bytesToReceive = (int)Math.Min(buffer.Length, size - sum);
count = client.Receive(buffer, 0, bytesToReceive, SocketFlags.None);
stream.Write(buffer, 0, count);
sum += count;
}
}
}
catch
{
if (File.Exists(destPath))
File.Delete(destPath);
client.Dispose();
}
}
You should never (have to) count on exceptions for regular program flow.
When the client side shuts down a socket, the server will receive a packet of 0 bytes, and continue to receive that whenever you call Receive. This causes your while loop to last forever. You should handle the situation that count is 0 and treat it as a regular "connection closed by client".
The exception you mentioned only occurs if the client side was unable to shut down properly.

Categories

Resources