I problemi...
1 - Errore nella comunicazione (SocketException)
2 - Come concateno il catch dell'errore nella texbox?
Ecco il client
codice:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
' Creo il TcpClient 127.0.0.1 porta 13000
Dim port As Int32 = 13000
Dim server As [String] = "127.0.0.1"
Dim client As New TcpClient(server, port)
Dim message As [String] = "PROVA"
' Traslo message in codice ASCII e lo metto nel Byte array
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(message)
' Creo lo stream per leggere e scrivere
Dim stream As NetworkStream = client.GetStream()
' Mando il messaggio al TcpServer
stream.Write(data, 0, data.Length)
' Notifico nella textbox l'invio del messaggio
stato_connessione.Text = ("Sent: {0}" & message)
' Ricevo la risposta del TcpServer
data = New [Byte](256) {}
Dim responseData As [String] = [String].Empty
Dim bytes As Int32 = stream.Read(data, 0, data.Length)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
stato_connessione.Text = ("Received: {0}" & responseData)
' Chiudo tutto
stream.Close()
client.Close()
' Notifico errori eventuali
Catch x As ArgumentNullException
errori.Text = "ArgumentNullException: {0}" 'come concateno quì la x?
Catch y As SocketException
errori.Text = "SocketException: {0}" 'come concateno quì la y?
End Try
End Sub
Ecco il server
codice:
Private Sub Main()
Dim server As TcpListener
server = Nothing
Try
' Setto il TcpListener su porta 13000 e localhost
Dim port As Int32 = 13000
Dim localAddr As IPAddress = IPAddress.Parse("127.0.0.1")
server = New TcpListener(localAddr, port)
' Mi metto in ascolto
server.Start()
' Buffer per leggere i dati in arrivo
Dim bytes(1024) As Byte
Dim data As String = Nothing
' Loop di ascolto
While True
connessione.Text = "Waiting for a connection... "
Dim client As TcpClient = server.AcceptTcpClient()
connessione.Text = "Connected!"
data = Nothing
' Creo lo stream per leggere e scrivere
Dim stream As NetworkStream = client.GetStream()
Dim i As Int32
' Loop per ricevere tutti i dati del client
i = stream.Read(bytes, 0, bytes.Length)
While (i <> 0)
' Converto i data bytes da ASCII a stringhe
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i)
connessione.Text = ("Received: {0}" & data)
data = data.ToUpper()
Dim msg As Byte() = System.Text.Encoding.ASCII.GetBytes(data)
' Invio risposta
stream.Write(msg, 0, msg.Length)
connessione.Text = ("Sent: {0}" & data)
i = stream.Read(bytes, 0, bytes.Length)
End While
' Chiudo tutto
client.Close()
End While
Catch e As SocketException
errore.Text = ("SocketException: {0}") 'come per il client non riesco a concatenare il catch di errore
'su consolle scrivevo così --- Console.WriteLine("SocketException: {0}", e)
Finally
server.Stop()
End Try
End Sub
End Class