作者sabertooth (剑齿虎)
看板C_Sharp
标题Re: [程式] c#写telnet
时间Thu Dec 16 19:21:09 2010
不好意思,又来烦大家了
我写了一支程式来做telnet连线的动作
并将接收到的资料列印在console
但卡在连上telnet server後(Unix)
原本应该列印出"login:"的地方
却列印出像是"?" "%"这类的乱码
我直觉是Encoding的问题
所以将所有编码方法全部试过,Unicode,ASCII,UTF7,UTF8,甚至default...
但都无法解决问题
如果我将server ip改为ptt.cc的话
则编码选default就可以显示进站画面,其他编码方式则还是显示乱码...
请问有熟悉这方面的前辈可以给点意见吗? =.=
我的code如下:
public class TcpClientSimple
{
public int Port;
public string IP = "";
public int TimeOut;
private TcpClient tcpClient;
public TcpClientSimple()
{
}
public TcpClientSimple(string strIP,int intPort,int intTimeOut)
{
SetTCP(strIP, intPort, intTimeOut);
}
public void Close()
{
tcpClient.Close();
}
public void SetTCP(string strIP, int intPort, int intTimeOut)
{
IP = strIP;
Port = intPort;
TimeOut = intTimeOut;
}
public void Send(string strCMD,out string strReceive, out string strError)
{
strError = "";
strReceive = "";
tcpClient = new TcpClient();
System.Diagnostics.DefaultTraceListener Deg = new
System.Diagnostics.DefaultTraceListener();
try
{
tcpClient.SendTimeout = TimeOut;
tcpClient.Connect(IP, Port);
NetworkStream networkStream = tcpClient.GetStream();
if (networkStream.CanWrite && networkStream.CanRead)
{
Byte[] sendBytes = Encoding.ASCII.GetBytes(strCMD);
networkStream.Write(sendBytes, 0, sendBytes.Length);
byte[] bytes = new byte[tcpClient.ReceiveBufferSize];
int BytesRead = networkStream.Read(bytes, 0,
(int)tcpClient.ReceiveBufferSize);
string returndata = Encoding.ASCII.GetString(bytes, 0, BytesRead);
Console.WriteLine(returndata);
networkStream.Close();
tcpClient.Close();
strReceive = returndata;
}
else if (!networkStream.CanRead)
{
tcpClient.Close();
}
else if (!networkStream.CanWrite)
{
tcpClient.Close();
}
}
catch (SocketException SE)
{
strError= SE.Message;
}
catch (System.IO.IOException IOE)
{
strError= IOE.Message;
}
catch (Exception e)
{
strError= e.Message;
}
}
}
static void Main()
{
TcpClientSimple tcp = new TcpClientSimple("192.168.1.1", 23, 10);
string strR;
string strE;
tcp.Send("CMD", out strR, out strE);
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 111.251.181.55
※ 编辑: sabertooth 来自: 111.251.181.55 (12/16 19:22)
2F:→ chchwy:你这样丢谁有办法帮你看orz... 12/25 23:00