Date time client based on TcpClient : TcpClient « Socket Network « VB.Net Tutorial






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

Public Class DateTimeClient
  Public Shared Sub Main()
    Dim args As String() = Environment.GetCommandLineArgs()

    Dim serverHost As String = "127.0.0.1"

    Try
      Dns.GetHostByName(serverHost)
    Catch ex As Exception
      Console.WriteLine("Can not find server, {0}", serverHost)
      Exit Sub
    End Try

    Dim tcpClient As New TcpClient()
    Dim networkStream As Stream

    Try
      tcpClient.Connect(serverHost, 13)

      networkStream = tcpClient.GetStream()
    Catch exc As Exception
      Console.WriteLine("Can not connect to {0}", serverHost)
      Exit Sub
    End Try

    Try
      If networkStream.CanRead Then
        Dim recvbytes(tcpClient.ReceiveBufferSize) As Byte
        Dim i As Integer = networkStream.Read(recvbytes, 0, CInt(tcpClient.ReceiveBufferSize))
        Dim datetime As String = Encoding.ASCII.GetString(recvbytes, 0, i)

        Console.WriteLine("Receive {0} bytes.", i)
        Console.WriteLine("Current server date/Time: {0}", datetime)
      Else
        Console.WriteLine("Network Input Stream is unreadable.")
        tcpClient.Close()
        Return
      End If
    Catch ec As Exception
      Console.WriteLine(ec.StackTrace.ToString())
      Exit Sub
    End Try

    tcpClient.Close()

  End Sub
End Class
Can not connect to 127.0.0.1








22.12.TcpClient
22.12.1.Create TcpClient
22.12.2.Date time client based on TcpClient