簡體   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