[英]Connecting to telnet server and send/recieve data
因此,我試圖連接到我的telnet服務器,該服務器可以正常工作。 它從服務器獲取第一批數據,要求我們輸入密碼進行連接。 但是,當我輸入密碼時,它什么也沒有做,並且沒有收到任何打印到我的控制台的內容。
輸出示例如下:
Connected to server.
Please enter password:
Response: MYPASSHERE
__BLANK RESPONSE FROM SERVER__
Response:
我目前正在使用此代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Threading;
namespace _7DaysServerManager
{
public class ServerSocket
{
private TcpClient client;
private Thread readWriteThread;
private NetworkStream networkStream;
private string password;
public ServerSocket(string ip, int port)
{
try
{
client = new TcpClient(ip, port);
Console.WriteLine("Connected to server.");
}
catch (SocketException)
{
Console.WriteLine("Failed to connect to server");
return;
}
//Assign networkstream
networkStream = client.GetStream();
//start socket read/write thread
readWriteThread = new Thread(readWrite);
readWriteThread.Start();
}
private void readWrite()
{
string command, recieved;
//Read first thing givent o us
recieved = read();
Console.WriteLine(recieved);
//Set up connection loop
while (true)
{
Console.Write("Response: ");
command = Console.ReadLine();
if (command == "exit")
break;
write(command);
recieved = read();
Console.WriteLine(recieved);
}
Console.WriteLine("Disconnected from server");
networkStream.Close();
client.Close();
}
public void write(string message)
{
networkStream.Write(Encoding.ASCII.GetBytes(message), 0, message.Length);
networkStream.Flush();
}
public string read()
{
byte[] data = new byte[1024];
string recieved = "";
int size = networkStream.Read(data, 0, data.Length);
recieved = Encoding.ASCII.GetString(data, 0, size);
return recieved;
}
}
}
我相信您需要您的代碼看起來像這樣:
message += Environment.NewLine;
byte[] messageBytes = Encoding.ASCII.GetBytes(message);
networkStream.Write(messageBytes, 0, messageBytes.Length);
也就是說,如果您不使用換行符來終止密碼,則服務器將不知道您已完成密碼輸入(TCP並非面向消息的,因此您沒有以任何方式繼續發送字節的事實就可以了)任何表明您已完成密碼發送的提示)。
還要注意,您應該使用從GetBytes()
返回的byte[]
的實際長度作為數據的長度。 對於ASCII,確實可以從消息長度中計算字節數,但是使用實際字節數是一種很好的習慣。 您可能並不總是在網絡代碼中使用ASCII。
最后,我建議您通過以下兩種方式更改代碼:
NetworkStream
在StreamReader
和StreamWriter
實例中,以使發送和接收文本更加容易(不要忘記將讀寫器的編碼設置為Encoding.ASCII
)。 StreamReader.ReadLineAsync()
以便在沒有顯式線程的情況下異步完成讀取。 如果您不切換到StreamReader
,則仍應在另一個線程中(異步或不異步)進行讀取,並且不要忘記您需要一直一直從緩沖區讀取數據,因為服務器的響應可能會一次調用Read()
不會收到此消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.