编写一个小的c#应用程序,它将接受客户端连接并相应地处理。我正在使用异步tcp套接字,因为我希望允许多个客户端同时向服务器发送数据。现在我不知道如何处理回调函数中收到的数据。下面是数据接收回调的代码。这里每次接收数据时都会打开输出文件并将数据附加到其中。我想在保存文件之前获取一些文件名/说一些客户端名称。我怎么做。我发送的客户端名称以“|”结尾用于区分其他数据的字符,但如何处理并将其保存到接收回调数据的变量中?任何帮助都会非常有用。
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.
}
}
答案 0 :(得分:0)
我已经为客户端和服务器的TCP网络制作了一个dll。 http://the7skulls.blogspot.com/2015/03/how-to-tcp-with-server-and-client-in-c.html