大家帮我看一下,下面的代码如何实现传送中文?

fanbl 2005-08-27 08:05:50
为什么下面的代码只能实现英文聊天,如果使用中文则出现乱码?请问大家如何解决?
public class Chat
{
private static IPAddress remoteIPAddress = IPAddress.Parse("127.0.0.1");
private static int remotePort;
private static int localPort;

[STAThread]
static void Main(string[] args)
{
Console.WriteLine("请输入本机端口");
localPort = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("请输入远程端口");
remotePort = Convert.ToInt16(Console.ReadLine());
Thread thread = new Thread(new ThreadStart(Receiver));
thread.Start();
while(true)
{
Send(Console.ReadLine());
}
}
private static void Send(string datagram)
{
UdpClient sender = new UdpClient();
IPEndPoint ipEndPoint = new IPEndPoint(remoteIPAddress,remotePort);
byte[] bytes = Encoding.ASCII.GetBytes(datagram);
sender.Send(bytes,bytes.Length,ipEndPoint);
sender.Close();
}
private static void Receiver()
{
UdpClient receivingUdpClient = new UdpClient(localPort);
IPEndPoint RemoteIPEndPoint = null;
Console.WriteLine("------------------Ready for chat!!!!!----------------------");
while(true)
{
byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIPEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine("-" + returnData);
}
}



}
...全文
70 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
fanbl 2005-08-27
  • 打赏
  • 举报
回复
楼上的朋友我这样byte[] bytes = Encoding.BigEndianUnicode.GetBytes(datagram);在接收端还是不能正确显示中文呀?大家帮帮我呀!
exboy 2005-08-27
  • 打赏
  • 举报
回复
出现乱码一般都编码出现问题了
byte[] bytes = Encoding.BigEndianUnicode.GetBytes(datagram);
fanbl 2005-08-27
  • 打赏
  • 举报
回复
我初学,上面的朋友能帮忙解释一下吗?我看不太明白?
wsh236 2005-08-27
  • 打赏
  • 举报
回复
using System;
using System.Text;

namespace ConvertExample
{
class ConvertExampleClass
{
static void Main()
{
string unicodeString = "This string contains the unicode character Pi(\u03a0)";

// Create two different encodings.
Encoding ascii = Encoding.ASCII;
Encoding unicode = Encoding.Unicode;

// Convert the string into a byte[].
byte[] unicodeBytes = unicode.GetBytes(unicodeString);

// Perform the conversion from one encoding to the other.
byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);

// Convert the new byte[] into a char[] and then into a string.
// This is a slightly different approach to converting to illustrate
// the use of GetCharCount/GetChars.
char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
string asciiString = new string(asciiChars);

// Display the strings created before and after the conversion.
Console.WriteLine("Original string: {0}", unicodeString);
Console.WriteLine("Ascii converted string: {0}", asciiString);
}
}
}

110,571

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧