繁体   English   中英

套接字服务器数据混乱

[英]Socket server data receive confusion

编写一个小型的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. 
  }
}

我已经制作了一个用于与客户端和服务器进行TCP网络连接的dll。 http://the7skulls.blogspot.com/2015/03/how-to-tcp-with-server-and-client-in-c.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM