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

时间:2017-06-02 21:32:12

标签: c# tcpclient tcplistener networkstream

我需要通过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.

1 个答案:

答案 0 :(得分:1)

谢谢,乔恩!

https://mysite.dev:35729/livereload.js