我会尝试解释下面的问题,我试过谷歌搜索答案,但首先,我不知道我应该谷歌搜索什么,我没有找到任何有意义的东西,我想知道如果有人能解释一下吗?非常感谢。
您好。我正在尝试使用TCP发送一个简单的网络数据包,我很容易使用UDP,因为它非常容易使用UDP,我想知道是否有人可以帮助我在TCP中做同等的事情?我尝试使用TcpClient,但它没有与UDP相同的Send方法?
Dog Food <tab3> :$30
Milk <tab3> :$3
Pizza Kit <tab3> :$5
Mt Dew <tab3> :$1.75
答案 0 :(得分: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();
}