简体   繁体   English

连接到telnet服务器并发送/接收数据

[英]Connecting to telnet server and send/recieve data

So I am trying to connect to my telnet server, which works. 因此,我试图连接到我的telnet服务器,该服务器可以正常工作。 It recives the first lot of data from the server which is us being asked to enter password to connect. 它从服务器获取第一批数据,要求我们输入密码进行连接。 But when I type in the password it does nothing and nothing that is recieved is printed to my console. 但是,当我输入密码时,它什么也没有做,并且没有收到任何打印到我的控制台的内容。

An example of the output is as follows: 输出示例如下:

Connected to server.
Please enter password:
Response: MYPASSHERE
__BLANK RESPONSE FROM SERVER__
Response:

在此处输入图片说明

I am currently using this code 我目前正在使用此代码

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;
        }
    }
}

I believe you need your code to look more like this: 我相信您需要您的代码看起来像这样:

message += Environment.NewLine;
byte[] messageBytes = Encoding.ASCII.GetBytes(message);
networkStream.Write(messageBytes, 0, messageBytes.Length);

Ie if you don't terminate the password with a newline character, the server doesn't know you're done entering the password (TCP is not message-oriented, so the fact that you didn't continue sending bytes in no way provides any indication that you're done sending the password). 也就是说,如果您不使用换行符来终止密码,则服务器将不知道您已完成密码输入(TCP并非面向消息的,因此您没有以任何方式继续发送字节的事实就可以了)任何表明您已完成密码发送的提示)。

Note also that you should use the actual length of the byte[] returned from GetBytes() as the length of the data. 还要注意,您应该使用从GetBytes()返回的byte[]的实际长度作为数据的长度。 For ASCII, it's true you can compute the number of bytes trivially from the message length, but using the actual byte count is a good habit to get into. 对于ASCII,确实可以从消息长度中计算字节数,但是使用实际字节数是一种很好的习惯。 You may not always be dealing with ASCII in networking code. 您可能并不总是在网络代码中使用ASCII。

Finally, I will suggest that you change your code in a couple of ways: 最后,我建议您通过以下两种方式更改代码:

  1. Wrap the NetworkStream in StreamReader and StreamWriter instances, to make sending and receiving text easier (don't forget to set the encoding to Encoding.ASCII for the reader and writer). NetworkStreamStreamReaderStreamWriter实例中,以使发送和接收文本更加容易(不要忘记将读写器的编码设置为Encoding.ASCII )。
  2. Read and write in different threads. 在不同的线程中读写。 Or even better, use StreamReader.ReadLineAsync() so that the reading is done asynchronously without an explicit thread. 甚至更好的方法是使用StreamReader.ReadLineAsync()以便在没有显式线程的情况下异步完成读取。

If you don't switch to StreamReader , you should still read (asynchronously or not) in a different thread, and don't forget that you need to keep reading from the buffer all the time, as a response from the server may or may not be received in a single call to Read() . 如果您不切换到StreamReader ,则仍应在另一个线程中(异步或不异步)进行读取,并且不要忘记您需要一直一直从缓冲区读取数据,因为服务器的响应可能会一次调用Read()不会收到此消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM