【问题标题】:Sending a packet in C# via TCP?通过 TCP 在 C# 中发送数据包?
【发布时间】:2018-04-12 15:23:20
【问题描述】:

我将尝试在下面解释我的问题,我已经尝试在谷歌上搜索答案,但首先,我真的不知道我应该在谷歌上搜索什么,我还没有找到任何对我有意义的东西,我想知道如果有人能解释一下?非常感谢。

你好。我正在尝试使用 TCP 发送一个简单的网络数据包,我很容易使用 UDP 完成它,因为使用 UDP 真的很容易,我想知道是否有人可以帮助我在 TCP 中做同样的事情?我尝试使用 TcpClient,但它没有与 UDP 相同的 Send 方法?

public void OnUdp()
{
    var client = new UdpClient(Host, Port);
    client.Send(rubbish, rubbish.Length);
}

【问题讨论】:

  • 尝试阅读 TcpClient 文档。它有一个例子。 msdn.microsoft.com/en-us/library/…
  • 也阅读this one
  • 查看 msdn 示例。该示例使用带有套接字类的 TCP。您可以将 Socket 类替换为任何继承套接字的类,如 TCPListener 和 TCPClient :docs.microsoft.com/en-us/dotnet/framework/network-programming/…
  • TCP 通过底层面向数据包的数据报网络提供面向连接的通信。 “发送” TCP“数据包”的概念是错误的。
  • 同意@spender,见comparison。使用 TCP,您发送字节流。接收者一次没有得到或得到一些,并且必须缓冲,直到它可以处理可操作的字节序列。当每个字节都可以单独操作时,这种微不足道的情况很少见。

标签: c# .net sockets tcp


【解决方案1】:

这是https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx的例子

static void Connect(String server, String message) 
{
  try 
  {
    // Create a TcpClient.
    // Note, for this client to work you need to have a TcpServer 
    // connected to the same address as specified by the server, port
    // combination.
    Int32 port = 13000;
    TcpClient client = new TcpClient(server, port);

    // Translate the passed message into ASCII and store it as a Byte array.
    Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);         

    // Get a client stream for reading and writing.
   //  Stream stream = client.GetStream();

    NetworkStream stream = client.GetStream();

    // Send the message to the connected TcpServer. 
    stream.Write(data, 0, data.Length);

    Console.WriteLine("Sent: {0}", message);         

    // Receive the TcpServer.response.

    // Buffer to store the response bytes.
    data = new Byte[256];

    // String to store the response ASCII representation.
    String responseData = String.Empty;

    // Read the first batch of the TcpServer response bytes.
    Int32 bytes = stream.Read(data, 0, data.Length);
    responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
    Console.WriteLine("Received: {0}", responseData);         

    // Close everything.
    stream.Close();         
    client.Close();         
  } 
  catch (ArgumentNullException e) 
  {
    Console.WriteLine("ArgumentNullException: {0}", e);
  } 
  catch (SocketException e) 
  {
    Console.WriteLine("SocketException: {0}", e);
  }

  Console.WriteLine("\n Press Enter to continue...");
  Console.Read();
}

【讨论】:

  • 这是一个非常糟糕的例子。它会在一条消息后关闭连接。对于初学者来说,这会引起很多悲伤。
  • 它还假设消息只有同样在 ASCII 字符集中的字符,没有任何参数验证。这使得静默破坏数据变得太容易了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多