Visualizzazione dei risultati da 1 a 4 su 4
  1. #1
    Utente di HTML.it L'avatar di elilo
    Registrato dal
    Aug 2007
    Messaggi
    149

    [VB.NET]Comunicazione PC con TCP

    Salve,
    Io vorrei far comunicare due applicazioni tramite il protocollo TCP. I client capiscono che devono comunicare con altri client tramite il polling a una tabella di un database online quindi non utilizza un server remoto

    Il codice che ho trovato per la comunicazione TCP è il seguente:
    codice:
    Imports System.Runtime.Serialization
    Imports System.Runtime.Serialization.Formatters.Binary
    Imports System.Net.Sockets
    Imports System.Net.Sockets.TcpClient
    Imports System.Net
    Imports System
    
    Public Class Form1
        Private moTcpClient, moTcpRxClient As TcpClient
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim moTcpServer = New TcpListener(13000)
            moTcpServer.Start()         'inizia la connessio tramite il TCP
            lb1.Text = ("Listening...")
            Button3.Enabled = False
            Button2.Enabled = True
            Button1.Enabled = False
            Do While Not moTcpServer.Pending
                Application.DoEvents()
            Loop
            moTcpRxClient = moTcpServer.AcceptTcpClient
            lb1.Text = "Connection received..."
            moTcpServer.Stop()
        End Sub
    
        Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    
            If TextBox1.Text <> "" And TextBox2.Text <> "" And IsNumeric(TextBox2.Text) Then
    
                Dim moLocalIP = Dns.GetHostByName(Dns.GetHostName)
                Dim ip = moLocalIP.AddressList(0).ToString
                '// Creates object
    
                Dim oPerson As New Person(TextBox1.Text, Int32.Parse(TextBox2.Text))
    
                '// Let's use dotNET TcpClient
                moTcpClient = New TcpClient()
                moTcpClient.Connect(ip, 13000)      'ip del destinatario, porta di uscita
                'moTcpClient.Connect("192.168.2.3", 13000)
                If moTcpClient.GetStream.CanWrite Then      'controlla se può scrivere
                    '// Serializes object in memory
                    Dim bf As New BinaryFormatter()
                    Dim oStream As New System.IO.MemoryStream()
                    bf.Serialize(oStream, oPerson)
                    '// Gets bytes...
                    Dim buf(CInt(oStream.Length)) As Byte
                    oStream.Position = 0
                    Dim iRet As Int32 = oStream.Read(buf, 0, buf.Length)
                    oStream.Close()
                    '// Send object through TCP-IP...
                    moTcpClient.GetStream.Write(buf, 0, buf.Length)
                    Button3.Enabled = True
                    Button2.Enabled = False
                End If
    
            Else
                MsgBox("errore")
            End If
    
        End Sub
    
        Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
            '// Deserializes object
            Dim oNs As NetworkStream = moTcpRxClient.GetStream
            If oNs.CanRead Then             'controlla se può leggere
                If oNs.DataAvailable Then   'controlla se sono presenti dei dati da leggere
                    '// Deserializes object
                    Try
                        Dim bf As New BinaryFormatter()
                        Dim oRxPerson As Person = CType(bf.Deserialize(oNs), Person)
                        risultato.Text += String.Format("Name:{0} Age:{1}", oRxPerson.Name, oRxPerson.Age)
                    Catch ex As Exception
                        '// Something wrong...
                        MessageBox.Show(ex.Message, "Deserialization error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    Finally
                        '// Closes connection
                        moTcpRxClient.Close()
                        ' btnDeser.Enabled = False
                        Button3.Enabled = False
                        Button2.Enabled = False
                        Button1.Enabled = True
                    End Try
                End If
            End If
        End Sub
    End Class
    
    '// Just a simple person object...
    <Serializable()> Public Class Person
        Public Name As String
        Public Age As Int32
        Public Sub New(ByVal name As String, ByVal age As Int32)
            Me.Name = name
            Me.Age = age
        End Sub
    End Class
    questo esempio si basa su un pulsante che mette in ascolto tramite un loop l'applicazione, un pulsante che server per inviare il testo e un pulsante che serve a riceverlo.

    come posso mettere l'ascolto continuo, ad esempio attraverso un timer e anche la ricezione non legata ad un pulsante.

  2. #2
    Utente di HTML.it L'avatar di elilo
    Registrato dal
    Aug 2007
    Messaggi
    149
    ho cercato in giro e nella documentazione di VB.NET ho trovato questi codici:

    Per il TcpListener e quindi lato server:

    codice:
    Imports System
    Imports System.IO
    Imports System.Net
    Imports System.Net.Sockets
    Imports System.Text
    Imports Microsoft.VisualBasic
    
    
    Class MyTcpListener
    
        Public Shared Sub Main()
    
    	Dim server As TcpListener
    	server=nothing
            Try
                ' Set the TcpListener on port 13000.
             Dim port As Int32 = 13000
             Dim localAddr As IPAddress = IPAddress.Parse("127.0.0.1")
    
             server = New TcpListener(localAddr, port)
             
             ' Start listening for client requests.
             server.Start()
             
             ' Buffer for reading data
                Dim bytes(1024) As Byte
                Dim data As String = Nothing
             
             ' Enter the listening loop.
             While True
                Console.Write("Waiting for a connection... ")
                
                ' Perform a blocking call to accept requests.
                ' You could also user server.AcceptSocket() here.
                Dim client As TcpClient = server.AcceptTcpClient()
                Console.WriteLine("Connected!")
                
                data = Nothing
                
                ' Get a stream object for reading and writing
                Dim stream As NetworkStream = client.GetStream()
                
                Dim i As Int32
                
                ' Loop to receive all the data sent by the client.
                i = stream.Read(bytes, 0, bytes.Length)
                While (i <> 0) 
                   ' Translate data bytes to a ASCII string.
                   data = System.Text.Encoding.ASCII.GetString(bytes, 0, i)
                        Console.WriteLine("Received: {0}", data)
                   
                   ' Process the data sent by the client.
                   data = data.ToUpper()
                        Dim msg As Byte() = System.Text.Encoding.ASCII.GetBytes(data)
                   
                   ' Send back a response.
                   stream.Write(msg, 0, msg.Length)
                        Console.WriteLine("Sent: {0}", data)
                  
                   i = stream.Read(bytes, 0, bytes.Length)
    
                End While
                
                ' Shutdown and end connection
                client.Close()
             End While
          Catch e As SocketException
             Console.WriteLine("SocketException: {0}", e)
          Finally
             server.Stop()
          End Try
          
          Console.WriteLine(ControlChars.Cr + "Hit enter to continue....")
          Console.Read()
       End Sub 'Main
    
    End Class 'MyTcpListener
    Per il TcpClient e quindi lato client:

    codice:
     
    Shared Sub Connect(server As [String], message As [String])
       Try
          ' Create a TcpClient.
          ' Note, for this client to work you need to have a TcpServer 
          ' connected to the same address as specified by the server, port
          ' combination.
          Dim port As Int32 = 13000
          Dim client As New TcpClient(server, port)
          
          ' Translate the passed message into ASCII and store it as a Byte array.
          Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(message)
          
          ' Get a client stream for reading and writing.
          '  Stream stream = client.GetStream();
          Dim stream As NetworkStream = client.GetStream()
          
          ' Send the message to the connected TcpServer. 
          stream.Write(data, 0, data.Length)
          
          Console.WriteLine("Sent: {0}", message)
          
          ' Receive the TcpServer.response.
          ' Buffer to store the response bytes.
          data = New [Byte](256) {}
          
          ' String to store the response ASCII representation.
          Dim responseData As [String] = [String].Empty
          
          ' Read the first batch of the TcpServer response bytes.
          Dim bytes As Int32 = stream.Read(data, 0, data.Length)
          responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
          Console.WriteLine("Received: {0}", responseData)
          
          ' Close everything.
          stream.Close()
          client.Close()
       Catch e As ArgumentNullException
          Console.WriteLine("ArgumentNullException: {0}", e)
       Catch e As SocketException
          Console.WriteLine("SocketException: {0}", e)
       End Try
       
       Console.WriteLine(ControlChars.Cr + " Press Enter to continue...")
       Console.Read()
    End Sub 'Connect
    ho provato a farli comunicare ma il server si pianta nel loop (While True)
    ho provato a inseririe il while in un thread separato ma va in errore comunque..come posso risolvere??

  3. #3
    scusate se mi intrometto....
    ma questo codice lo devo incollare nell'applicazione windows o in quella console???
    ho provato a usarrlo cm appl. windows perchè mi interessava ma mi da parecchi errori...
    mi dice che il nome "risultato"
    non esiste... cm poxo fare?????

  4. #4
    Utente di HTML.it L'avatar di oregon
    Registrato dal
    Jul 2005
    residenza
    Roma
    Messaggi
    36,480
    Hai notato che nel codice c'e' scritto

    risultato.Text

    ?

    Quindi, vuol dire che risultato e' il nome di un textbox che deve essere presente sul form ... e tu ce lo devi mettere ...
    No MP tecnici (non rispondo nemmeno!), usa il forum.

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.