C# : Socket 接收中文显示乱码的解决办法

由 Programming C# 3.0 示例改编

AsyncNetClient.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Text;

namespace AsyncNetClient
{
    public class AsynchNetworkClient
    {
        private NetworkStream streamToServer;

        static public int Main()
        {
			string str;
            Console.Write("input:");
			str = Console.ReadLine();
            if (str.Length > 20)
            {
                Console.WriteLine("提示: 输入字符串长度 <= 20");
                return 4;
            }
            AsynchNetworkClient client = new AsynchNetworkClient("localhost",65000);
            if( client != null && str!=null) return client.Run(str);
            else return 4;
        }

        public AsynchNetworkClient(string ip, int port)
        {
            string serverName = ip;
            try
            {
                Console.WriteLine("Connecting to {0}", serverName);
                TcpClient tcpSocket = new TcpClient(serverName, port);
                streamToServer = tcpSocket.GetStream();
            }
            catch (Exception e){
                Console.WriteLine(e.ToString());
            }
        }

        public int Run(string str)
        {
            if (streamToServer == null)
            {
                Console.WriteLine("connect to Server failed !");
                return -1;
            }
            string message;
            if( str != "") message= str;
            else return -1;
            Console.WriteLine("Send to server: {0}", message);

            // create a streamWriter and use it to
            // write a string to the server
            StreamWriter writer = new StreamWriter(streamToServer);
            writer.WriteLine(message);
            writer.Flush();

            // 使用System.Text.Encoding.Default 告诉 StreamReader采用目前操作系统的编码即可
            StreamReader reader = new StreamReader(streamToServer,Encoding.Default);
            string strResponse = reader.ReadLine();
            streamToServer.Close();
            Console.WriteLine("Received: {0}", strResponse);
            return 0;
        }
    }
}


编译 csc.exe AsyncNetClient.cs

运行 AsyncNetClient.exe



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值