gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 12:05:09 25 4
gpt4 key购买 nike

我正在尝试在Visual Studio中设置服务器和客户端模拟,但是在使其正常工作方面存在问题。两个程序都运行,但是我得到的全部是输出“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();

}

最佳答案

问题出在行中

 string temp = recbuffer.ToString();

在客户端代码和服务器代码上均如此。

您需要更改为
 string temp = System.Text.Encoding.Default.GetString(recbuffer);

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

关于c# - 服务器-客户端Windows窗体应用程序C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26563997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com