【发布时间】:2015-03-15 20:03:16
【问题描述】:
编写一个小的 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.
}
}
【问题讨论】:
-
UDP 或 TCP 让世界变得与众不同
-
我正在使用 TCP。更改线程名称。