Reputation: 816
Writing a small c# application which would accept client connection and process accordingly. I'm using asynchronous tcp socket for this as I would like to allow multiple clients to send data to server simultaneously. Now I'm not sure how do I handle data received inside the callback function. Below is the code for Data receiving callback. Here each time a data is receive it opens the output file and append data to it. I want to get some file name / say some client name before saving file. How do I do that. I'm sending the client name terminated by "|" character to distinguish from other data but how do I handle and save it to a variable from data receiving callback? Any help would be highly appriciable.
public void OnDataReceived(IAsyncResult ar)
{
StateObject state = (StateObject)ar.AsyncState;
Socket clientSocket = state.m_currentSocket;
BinaryWriter writer;
string fileSavePath = m_strCurrFolder[m_currClientNumber] + "File";
int bytesRead = clientSocket.EndReceive(ar);
if (bytesRead > 0)
{
//If the file doesn't exist, create a file with the filename got from server. If the file exists, append to the file.
if (!File.Exists(fileSavePath))
{
writer = new BinaryWriter(File.Open(fileSavePath, FileMode.Create));
}
else
{
writer = new BinaryWriter(File.Open(fileSavePath, FileMode.Append));
}
writer.Write(state.dataBuffer, 0, bytesRead);
writer.Flush();
writer.Close();
// Recursively receive the rest file.
try
{
clientSocket.BeginReceive(state.dataBuffer, 0, StateObject.BufferSize, 0, new AsyncCallback(OnDataReceived), state);
}
catch
{
if (!clientSocket.Connected)
{
//MessageBox.Show(Properties.Resources.DisconnectMsg);
MessageBox.Show("Catched from OnDataReceived!");
}
}
}
else
{
// Signal if all the file received.
}
}
Upvotes: 1
Views: 124
Reputation: 351
I have made a dll for TCP networking with a client and server. http://the7skulls.blogspot.com/2015/03/how-to-tcp-with-server-and-client-in-c.html
Upvotes: 0