language中文

Socket通信中文字符乱码问题解决方法

visibility 1,334 comment 0 access_time 13 years ago

自己做了个Windows服务,监听本机的TCP5678端口,并且响应后返回给客户端一个随机的字符串,这个字符串中包含有中文字符。但是传输的过程中客户端接收到的字符串中文乱码了,于是自己检查了下客户端和服务器端的读取bytes的编码是否统一

客户端是:

UTF8Encoding encoder = new UTF8Encoding();
textBoxQuote.Text =encoder.GetString(buffer);

服务器端是:

Socket clientSocket = listener.AcceptSocket();
               string message = GetRandomQuoteOfTheDay();
               UTF8Encoding encoder = new UTF8Encoding();
               byte[] buffer = encoder.GetBytes(message);
               clientSocket.Send(buffer, buffer.Length, 0);
               clientSocket.Close();

两个都是UTF-8格式的但是为什么出现了乱码的情况呢?

检查了下读取随机字符串的那个文件的格式原来是ASCII格式的,于是自己另存为utf-8格式的这个问题就解决了,因为我那个文件用记事本创建默认保存格式不是utf-8的,所以大家如果遇到此类情况,最好检查下你传输的字符串的来源文件的格式是否统一。

本文同时发布在:http://www.xmaspx.com

info Last modified by Raymond 13 years ago copyright This page is subject to Site terms.

Subscribe newsletter

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts

More from Kontext

visibility 14
thumb_up 0
access_time 11 days ago
Get Started on .NET 5 with Apache Spark
visibility 572
thumb_up 1
access_time 10 months ago
Get Started on Reunified .NET 5
visibility 83
thumb_up 0
access_time 13 months ago