C# 套接字服务器数据接收混乱
编写一个小型c#应用程序,它将接受客户端连接并进行相应的处理。我使用异步tcp套接字实现这一点,因为我希望允许多个客户端同时向服务器发送数据。现在我不确定如何处理回调函数中接收到的数据。下面是数据接收回调的代码。在这里,每次接收数据时,它都会打开输出文件并向其追加数据。在保存文件之前,我想获取一些文件名/说出一些客户端名称。我该怎么做呢。我正在发送以“|”字符结尾的客户端名称,以区别于其他数据,但如何处理并将其保存到数据接收回调的变量中?任何帮助都是非常值得的C# 套接字服务器数据接收混乱,c#,sockets,tcp,C#,Sockets,Tcp,编写一个小型c#应用程序,它将接受客户端连接并进行相应的处理。我使用异步tcp套接字实现这一点,因为我希望允许多个客户端同时向服务器发送数据。现在我不确定如何处理回调函数中接收到的数据。下面是数据接收回调的代码。在这里,每次接收数据时,它都会打开输出文件并向其追加数据。在保存文件之前,我想获取一些文件名/说出一些客户端名称。我该怎么做呢。我正在发送以“|”字符结尾的客户端名称,以区别于其他数据,但如何处理并将其保存到数据接收回调的变量中?任何帮助都是非常值得的 public void OnDat
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.
}
}
我制作了一个dll,用于与客户端和服务器进行TCP网络连接。
UDP或TCP使世界变得不同我正在使用TCP。更改线程名称。