繁体   English   中英

在服务器-客户端TCP应用程序中发送和接收byte []

[英]Send and receive byte[] in server-client TCP application

我需要通过NetworkStream从客户端向服务器发送和接收字节。 我知道如何与字符串进行通信,但是现在我需要发送和接收字节。

例如,类似这样的内容:

static byte[] Receive(NetworkStream netstr)
{
    try
    {
        byte[] recv = new Byte[256];

        int bytes = netstr.Read(recv, 0, recv.Length); //(**This receives the data using the byte method**)
        return recv;
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error!\n" + ex.Message + "\n" + ex.StackTrace);

        return null;
    }



}

static void Send(NetworkStream netstr, byte[] message)
{
    try
    {
        netstr.Write(message, 0, message.Length);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error!\n" + ex.Message + "\n" + ex.StackTrace);
    }
}

服务器:

        private void prejmi_click(object sender, EventArgs e)
        {
            const string IP = "127.0.0.1";
            const ushort PORT = 54321;
            TcpListener listener = new TcpListener(IPAddress.Parse(IP), PORT);
            listener.Start();
            TcpClient client = listener.AcceptTcpClient();
            NetworkStream ns = client.GetStream();

            byte[] data = Receive(ns)

}

客户:

        private void poslji_Click(object sender, EventArgs e)
        {
            const string IP = "127.0.0.1";
            const ushort PORT = 54321;

            TcpClient client = new TcpClient();
            client.Connect(IP, PORT);

            string test="hello";
            byte[] mybyte=Encoding.UTF8.GetBytes(test);
            Send(ns,mybyte);
}

但这不是正确的方法,因为服务器端的byte []数据的长度始终为256。

谢谢,乔恩!

 static byte[] Receive(NetworkStream netstr)
        {
            try
            {
                // Buffer to store the response bytes.
                byte[] recv = new Byte[256];

                // Read the first batch of the TcpServer response bytes.
                int bytes = netstr.Read(recv, 0, recv.Length); //(**This receives the data using the byte method**)

                byte[] a = new byte[bytes];

                for(int i = 0; i < bytes; i++)
                {
                    a[i] = recv[i];
                }

                return a;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error!\n" + ex.Message + "\n" + ex.StackTrace);

                return null;
            }

        }

        static void Send(NetworkStream netstr, byte[] message)
        {
            try
            {
                //byte[] send = Encoding.UTF8.GetBytes(message.ToCharArray(), 0, message.Length);
                netstr.Write(message, 0, message.Length);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error!\n" + ex.Message + "\n" + ex.StackTrace);
            }
        }

暂无
暂无

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

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