Hi,
I'm a newbe for .NET and I'm trying to learn Vb.NET.
I want to make a little console program (server) that, given the local ip and port, wait a client connection.
When the client connects to the server, I want tah the server wrote on the console the client messages, and when the client close the connection the server wait new client.
However now when client connect, the server close application. Where is the problem?
The code is as follows:
Many thanks (and sorry for my english)
Max
I'm a newbe for .NET and I'm trying to learn Vb.NET.
I want to make a little console program (server) that, given the local ip and port, wait a client connection.
When the client connects to the server, I want tah the server wrote on the console the client messages, and when the client close the connection the server wait new client.
However now when client connect, the server close application. Where is the problem?
The code is as follows:
VB.NET:
Imports System.IO
Imports System.Net
Imports System.Net.Dns
Imports System.Net.Sockets
Imports System.Threading
Imports System.Text
Module Module1
Private Sub usage(ByVal io As String, Optional ByVal errore As String = "")
Console.WriteLine("Usage: " + io + " <ip> <port>")
Console.WriteLine(errore)
Environment.Exit(0)
End Sub
Sub Main()
Dim io = System.IO.Path.GetFileName(System.Environment.GetCommandLineArgs()(0))
Dim i As Integer
Dim argc As Integer = My.Application.CommandLineArgs.Count
Dim host As IPAddress = Nothing
Dim localAddr As IPAddress = Nothing
Dim ip, porta, ipclient As String
Dim server As TcpListener
Dim client As TcpClient
Dim networkStream As NetworkStream
Dim bytes() As Byte
Dim clientdata As String
If argc <> 2 Then
usage(io.ToLower)
Else
ip = My.Application.CommandLineArgs(0).ToString
porta = My.Application.CommandLineArgs(1).ToString
End If
Try
host = GetHostByName(ip).AddressList(0)
Catch ex As System.Exception
usage(io.ToLower, "Invalid IP address")
End Try
If Not IsNumeric(porta) Then
usage(io.ToLower, "Invalid porta")
End If
localAddr = IPAddress.Parse(host.ToString)
server = New TcpListener(localAddr, porta)
Try
server.Start()
Console.WriteLine(System.DateTime.Now + " > waiting connection on port " + porta + "....")
client = server.AcceptTcpClient
Dim ipend As Net.IPEndPoint = client.Client.RemoteEndPoint
ipclient = ipend.Address.ToString
Console.WriteLine(System.DateTime.Now + " > ....Connect from " + ipclient)
networkStream = client.GetStream()
ReDim bytes(client.ReceiveBufferSize)
networkStream.Read(bytes, 0, CInt(client.ReceiveBufferSize))
clientdata = Encoding.ASCII.GetString(bytes)
Console.WriteLine(System.DateTime.Now + " > Client wrote: " + clientdata)
'client.Close()
Catch ex As Exception
Console.WriteLine(System.DateTime.Now + " --> " + ex.Message.ToString)
End Try
End Sub
End Module
Many thanks (and sorry for my english)
Max