服务器客户端Windows窗体应用程序C#

本文关键字:应用程序 窗体 Windows 客户端 服务器 | 更新日期: 2023-09-27 18:27:58

我正试图在visualstudio中设置一个服务器和客户端模拟,但在运行时遇到了问题。这两个程序都在运行,但我得到的只是"System.Byte[]"输出。这是我第一次尝试制作这样的应用程序。我从控制台应用程序中提取了一些代码,所以我一直在尝试调整它以适应windows窗体

这是客户端代码:

private void Form1_Load(object sender, EventArgs e)
    {
        textBox1.Text = "Client has Made Connection to Server OK";
    }
    private void button1_Click(object sender, EventArgs e)
    {
        Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        int port;
        port = int.Parse(textBox4.Text);
        IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(textBox5.Text), port);

        sck.Connect(endpoint);
        //textBox1.Text = "Client has Made Connection to Server OK";
        Byte[] recbuffer = new byte[255];
        int rec = sck.Receive(recbuffer, 0, recbuffer.Length, 0);
        Array.Resize(ref recbuffer, rec);
        string temp = recbuffer.ToString();
        textBox2.Text = "Received: {0}" + temp;
        // sending string to server
        string msg = textBox3.Text;
        byte[] msgbuffer = Encoding.Default.GetBytes(msg);
        sck.Send(msgbuffer, 0, msgbuffer.Length, 0);

        Console.Read();
    }

这是服务器代码:

private void Form1_Load(object sender, EventArgs e)
    {
        IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9939);
        Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        sck.Bind(ip);
        sck.Listen(0);
        Socket acc = sck.Accept();
        textBox1.Text = "Connection has been made to the server from the Client";
        byte[] buffer = Encoding.Default.GetBytes("Hello sent from Server to Client");
        string displayBuffer = buffer.ToString();
        textBox2.Text = displayBuffer;
        acc.Send(buffer, 0, buffer.Length, SocketFlags.None);
        byte[] recbuffer = new byte[255];
        int rec = acc.Receive(recbuffer, 0, recbuffer.Length, 0);
        Array.Resize(ref recbuffer, rec);
        string temp = recbuffer.ToString();
        textBox3.Text = "received from client the string: " + temp;
        Console.Read();
    }

服务器客户端Windows窗体应用程序C#

问题出在行

 string temp = recbuffer.ToString();

客户端代码和服务器代码。

您需要更改为

 string temp = System.Text.Encoding.Default.GetString(recbuffer);

通过ToString方法请求字节数组返回字符串只返回类的名称,因为字节数组无法将自己转换为字符串。