【问题标题】:Send text string via TCP?通过 TCP 发送文本字符串?
【发布时间】:2013-02-27 01:38:30
【问题描述】:

我刚刚阅读并测试了this 伟大文章的代码,以了解 TCP 客户端和服务器。

现在我需要做(我希望)非常简单的事情我需要从 TCP 客户端向 TCP 服务器发送一些字符串。

字符串是序列化的对象,实际上是一个XML。

我不明白我必须将此代码包含在 TCP 客户端和 TCP 服务器中的什么位置。

TCP 客户端:

static void Main(string[] args)
    {

        while (true)
        {
            String server = "192.168.2.175"; // args[0]; // Server name or IP address

            // Convert input String to bytes
            byte[] byteBuffer = Encoding.ASCII.GetBytes("1024"); // Encoding.ASCII.GetBytes(args[1]);

            // Use port argument if supplied, otherwise default to 8080
            int servPort = 1311;  // (args.Length == 3) ? Int32.Parse(args[2]) : 8080;//7 ;

            TcpClient client = null;
            NetworkStream netStream = null;

            try
            {
                // Create socket that is connected to server on specified port
                client = new TcpClient(server, servPort);

                Console.WriteLine("Connected to server... sending echo string");

                netStream = client.GetStream();

                // Send the encoded string to the server
                netStream.Write(byteBuffer, 0, byteBuffer.Length);

                Console.WriteLine("Sent {0} bytes to server...", byteBuffer.Length);

                int totalBytesRcvd = 0; // Total bytes received so far
                int bytesRcvd = 0; // Bytes received in last read

                // Receive the same string back from the server
                while (totalBytesRcvd < byteBuffer.Length)
                {
                    if ((bytesRcvd = netStream.Read(byteBuffer, totalBytesRcvd,
                    byteBuffer.Length - totalBytesRcvd)) == 0)
                    {
                        Console.WriteLine("Connection closed prematurely.");
                        break;
                    }
                    totalBytesRcvd += bytesRcvd;
                }
                Console.WriteLine("Received {0} bytes from server: {1}", totalBytesRcvd,
                Encoding.ASCII.GetString(byteBuffer, 0, totalBytesRcvd));

            }
            catch (Exception ex)
            {
                // http://stackoverflow.com/questions/2972600/no-connection-could-be-made-because-the-target-machine-actively-refused-it
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (netStream != null)
                    netStream.Close();
                if (client != null)
                    client.Close();
            }
            Thread.Sleep(1000);
        }

    }

TCP 服务器

class Program
{

    private const int BUFSIZE = 32; // Size of receive buffer

    static void Main(string[] args)
    {


        int servPort = 1311; // (args.Length == 1) ? Int32.Parse(args[0]) : 8080;

        TcpListener listener = null;

        try
        {
            // Create a TCPListener to accept client connections
            listener = new TcpListener(IPAddress.Any, servPort);
            listener.Start();
        }
        catch (SocketException se)
        {
            // IPAddress.Any
            Console.WriteLine(se.ErrorCode + ": " + se.Message);
            //Console.ReadKey();
            Environment.Exit(se.ErrorCode);

        }

        byte[] rcvBuffer = new byte[BUFSIZE]; // Receive buffer
        int bytesRcvd; // Received byte count
        for (; ; )
        { // Run forever, accepting and servicing connections
            // Console.WriteLine(IPAddress.Any);
            TcpClient client = null;
            NetworkStream netStream = null;
            //Console.WriteLine(IPAddress.None);

            try
            {
                client = listener.AcceptTcpClient(); // Get client connection
                netStream = client.GetStream();
                Console.Write("Handling client - ");

                // Receive until client closes connection, indicated by 0 return value
                int totalBytesEchoed = 0;
                while ((bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0)
                {
                    netStream.Write(rcvBuffer, 0, bytesRcvd);
                    totalBytesEchoed += bytesRcvd;
                }
                Console.WriteLine("echoed {0} bytes.", totalBytesEchoed);

                // Close the stream and socket. We are done with this client!
                netStream.Close();
                client.Close();

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                netStream.Close();
            }
        }
    }
}

【问题讨论】:

  • 我强烈建议你使用 WCF,而不是自己实现所有的东西。在 WCF 中,您创建接口(服务契约)和实现(服务),框架将所有通信/协议细节抽象出来。
  • @HighCore 在我的应用程序架构中,我必须实现 TCP 客户端/服务器的组合。所以“客户端”和“服务器”将拥有这些组合的东西。问题:我是否在两台机器上都安装了 WCF 应用程序?你的意思是它应该像“WcfService1”客户端和“WcfService2”服务器项目?所以工作站有“WcfService1”和服务器“WcfService2”?
  • WCF 是 .Net 框架的一部分。我不明白你的问题。无论如何,你必须在目标机器上安装 .Net 框架,否则你的代码将无法运行。
  • 不,您可以使用WCF Duplex 在服务器和客户端之间进行双向通信。
  • @HighCore 谢谢!我现在正在阅读 stackoverflow.com/questions/6064823/… 并让您对 WCF Duplex 发表评论。可能这正是我需要的......

标签: c# .net string tcp


【解决方案1】:

将我的评论转化为答案:

我强烈建议您使用 WCF,而不是自己实现所有的东西。在 WCF 中,您创建接口(服务契约)和实现(服务),框架将所有通信/协议细节抽象出来。

您可以使用WCF Duplex 在服务器和客户端之间进行双向通信

【讨论】:

    【解决方案2】:

    您给出的示例是一个简单的“镜像”,TCP 服务器将其从客户端接收到的数据发送回客户端。

    您要发送的数据在 byteBuffer 变量中(我相信您当前正在发送文本“1024”)。因此,您可以使用所需的 XML 序列化数据对其进行初始化,而不是使用“1024”对其进行初始化。

    相反,在客户端,您可以简单地在服务器端对数据(即您的 XML 对象)执行任何您需要的操作,而不是将数据回显给客户端。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-28
      • 2014-01-01
      • 2016-03-02
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 2020-02-17
      • 2016-10-11
      相关资源
      最近更新 更多