【发布时间】:2018-06-29 07:27:47
【问题描述】:
所以我正在做一个非常简单的项目,一个连接到可以接收数据的预制服务器的客户端。 我正在尝试发送一个缓冲区,但是当它恢复缓冲区时,即使我正在尝试发送“Hello World!”,它也会获得中文字符。
我如何正确编码我的缓冲区,以便当服务器接收到它时,它不会接收到中文字符?
还有..客户端发送完后就卡住了,这是为什么呢?
Visual representation showing what it looks like
const string IP = "127.0.0.1";
const int port = 12345;
TcpClient Client = new TcpClient();
public Form1()
{
Client.NoDelay = true;
InitializeComponent();
}
private void SendMessage()
{
//Create the message we are going to send.
string texttoSend = DateTime.Now.ToString();
//Create a network stream to get all the data that comes and goes through the client.
NetworkStream nwStream = Client.GetStream();
//Convert out string message to a byteArray because we will send it as a buffer later.
byte[] bytesToSend = Encoding.ASCII.GetBytes(texttoSend);
//Write out to the console what we are sending.
Console.WriteLine("Sending: " + texttoSend);
//Use the networkstream to send the byteArray we just declared above, start at the offset of zero, and the size of the packet we are sending is the size of the messages length.
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
//Recieve the bytes that are coming from the other end (server) through the client and store them in an array.
byte[] bytesToRead = new byte[Client.ReceiveBufferSize];
//read the bytes, starting from the offset 0, and the size is what ever the client has recieved.
int bytesRead = nwStream.Read(bytesToRead, 0, Client.ReceiveBufferSize);
//Decode the bytes we just recieved using the Encoding.ASCII.GetString function and give it the correct parameters
//1. What it should decode
//2. Starting to decode from what offset
//3. How much do we want to decode?
Console.WriteLine("Recieved: " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
Console.ReadLine();
//Close the client so we're not leaving it open for people to eavesdrop.
Client.Close();
}
private async Task Connect()
{
try
{
await Client.ConnectAsync(IP, port);
btnConnect.BackColor = Color.Green;
btnConnect.Text = "Connected.";
}
catch (Exception e)
{
MessageBox.Show("Server refused the connection.", "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning);
Debug.Print(e.ToString());
}
}
private async void btnConnect_ClickAsync(object sender, EventArgs e)
{
await Connect();
}
private void btnSendAll_Click(object sender, EventArgs e)
{
SendMessage();
}
【问题讨论】:
-
TCP 不关心语言,更不用说中文了。它只是发送字节。问题出在其他地方
-
有什么理由让您看起来像是寄给自己的?服务器代码在哪里?
-
服务器是学校给我们定制的服务器,我无法访问源代码,也无权访问它。
-
@MickyD 我只能访问端口和运行它的 IP,我显然是在我的 PC 上启动它。
-
请不要破坏您的问题。这样一来,您实际上就是在使本网站志愿者发布的所有帮助、努力和答案都过时了,这对他们来说根本不公平。
标签: c# .net encoding tcp buffer