VB.NET writing a telnet client using system.net.tcpclient

徘徊边缘 提交于 2019-12-20 04:28:44

问题


This isn't working for me when I connect to my solaris box

The server is sending back

??%

does anyone know what i'm doing wrong

Imports System.Net
    Imports System.Net.Sockets
    Imports System.Text

    Public Class TelnetClient

        Private _hostname As String = "myserver"
        Private _username As String = "user"
        Private _password As String = "pass"

        Private _port As Integer = 23
        Private _client As TcpClient
        Private _data As String

        Private _sendbuffer(128) As Byte
        Private _readbuffer(128) As Byte
        Private _bytecount As Integer

        Private _stream As NetworkStream

        Private Sub Send(ByVal Text As String)
            _sendbuffer = Encoding.ASCII.GetBytes(Text)
            _stream.Write(_sendbuffer, 0, _sendbuffer.Length)
        End Sub

        Private Sub Read()
            _bytecount = _stream.Read(_readbuffer, 0, _readbuffer.Length)
            _data = Encoding.ASCII.GetString(_readbuffer)
        End Sub

        Public Sub Connect()

            _client = New TcpClient(_hostname, _port)

            _stream = _client.GetStream

            Send(_username)
            Read()

            MsgBox(_data)

            Send(_password)
            Read()

            _stream.Close()

            _client.Close()





        End Sub

    End Class

回答1:


The ??% that you are getting from the server is part of the Telnet options negotiation. You need to do the options negotiation before any other communication can take place.




回答2:


The Read() method in the code above is decoding the entire _readbuffer when _stream.Read() may only fill part of the buffer. _bytecount will tell you how many bytes you can decode.

Can I suggest using a StreamReader. The StreamReader.ReadLine() method will block until a newline is received and give you a string back.




回答3:


You're getting those because you're trying to translate raw data before its collected. You need to add in a about a 2 second sleep between communication between telnet functions.

Public Sub Connect()

        _client = New TcpClient(_hostname, _port)

        _stream = _client.GetStream

        Threading.Thread.Sleep(2000)

        Send(_username)
        Threading.Thread.Sleep(2000)
        Read()

        MsgBox(_data)

        Send(_password)
        Threading.Thread.Sleep(2000)
        Read()

        _stream.Close()

        _client.Close()


来源:https://stackoverflow.com/questions/3508936/vb-net-writing-a-telnet-client-using-system-net-tcpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!