Trasmissione di dati fra due o più programmi Gambas mediante la Classe Socket del Componente gb.net

Da Gambas-it.org - Wikipedia.

I Socket sono definiti come endpoint di comunicazione e si riferiscono a un mezzo di comunicazione del computer che utilizza indirizzi IP e porte.

I Socket vengono generalmente utilizzati per inviare dati tra due computer su una rete, ma possono anche essere utilizzati per comunicare tra due programmi sullo stesso computer.

La struttura base di funzionamento delle Socket è di tipo Client/Server.
Supponiamo di avere due processi p1 e p2. Il processo p2 ha bisogno del processo p1 per eseguire un determinato compito. Il processo p1 offrirà al processo p2 tale servizio, esso perciò sarà il "Servente" ovvero il Server. Il processo p2 che richiede il servizio sarà dunque il "Cliente", ovvero il Client.

Questa pagina mostrerà come creare un programma Server Socket con le Classi "ServerSocket" e "Socket" del Componente Gambas gb.net e due o più programmi Client Socket mediante la Classe "Socket". [Nota 1]
Dopo aver lanciato il Server e i due Client, si potrà inviare del testo dal primo Client al secondo e viceversa.

Creiamo il "Server Socket":

Private Button1 As Button
Private TextArea1 As TextArea
Private Clients As New Object[]
Private ServerSocket1 As ServerSocket


Public Sub Form_Open()
 
 With Button1 = New Button(Me) As "Button1"
   .Text = "   Attiva il Server...  "
   .W = .Font.TextWidth(.Text)
   .H = .Font.TextHeight(.Text) * 3
   .X = (Me.W / 2) - (.W / 2)
   .Y = Me.H * 0.05
 End With
 With TextArea1 = New TextArea(Me) As "TextArea1"
  .W = Me.W * 0.8
  .H = Me.H * 0.6
  .X = (Me.W / 2) - (.W / 2)
  .Y = Button1.Y + Button1.H + 10
End With
 With ServerSocket1 = New ServerSocket As "ServerSocket1"
' Si assegna un numero qualsiasi della porta:
   .Port = 12345
   .Type = Net.Internet
 End With 
   
End

Public Sub Form_Close()

 ServerSocket1.Close
 
End


Public Sub Button1_Click()
 
' Nell'argomento del Metodo ".Listen() si passa il numero di "Client" che dovranno essere serviti:
 ServerSocket1.Listen(2)
 
 If ServerSocket1.Status = Net.Active Then
   Button1.Enabled = False
   Button1.Background = Color.Green
   Button1.Text = "Server attivo !"
   Me.Caption &= "In attesa sulla Porta: " & ServerSocket1.Port & gb.CrLf
 End If

End

Public Sub ServerSocket1_Connection(HostIP As String)
 
 Dim sock As Socket
 
 Me.Caption = "Connessione da... " & HostIP
 
 sock = ServerSocket1.Accept()
 Clients.Add(sock)
 Object.Attach(sock, Me, "Sock")
 
 Write #Clients[Clients.Max], "Connessione al Server accettata !\n"
 
End


Public Sub Sock_Read()
 
 Dim msg As String
 
 If Last.Status <> Net.Connected Then Return
 
 Read #Last, msg, Lof(Last)
 
 TextArea1.Text &= msg
 
 If Clients.Count = 1 Then
   Write #Clients[0], msg
 Else
   If Last.RemotePort == Clients[0].RemotePort Then
     Write #Clients[1], msg
   Else
     Write #Clients[0], msg
   Endif
 Endif
 
End


Quindi scriviamo il codice del primo "Client Socket".
Bisognerà individuare il proprio indirizzo IP privato. Questo indirizzo IP privato potrà essere ricavato lanciando da Terminale il comando: ~$ hostname -I

Private SockClient1 As Socket
Private Button1 As Button
Private Button2 As Button
Private TextArea1 As TextArea


Public Sub Form_Open()
 
 With Me
   .Center
   .W = 400
   .H = 400
 End With
 With Button1 = New Button(Me) As "Button1"
   .Text = "   Attiva connessione   "
   .W = .Font.TextWidth(.Text)
   .H = .Font.TextHeight(.Text) * 3
   .X = (Me.W / 2) - (.W / 2)
   .Y = Me.H * 0.05
 End With
 With TextArea1 = New TextArea(Me) As "TextArea1"
   .W = Me.W * 0.8
   .H = Me.H * 0.6
   .X = (Me.W / 2) - (.W / 2)
   .Y = Button1.Y + Button1.H + 10
 End With
 With Button2 = New Button(Me) As "Button2"
   .Text = "   INVIA TESTO   "
   .W = .Font.TextWidth(.Text)
   .H = .Font.TextHeight(.Text) * 3
   .X = (Me.W / 2) - (.W / 2)
   .Y = TextArea1.Y + TextArea1.H + 10
 End With
 
End

Public Sub Form_Close()
 
 If SockClient1.Status > Net.Inactive Then SockClient1.Close
 
End


Public Sub Button1_Click()
 
 SockClient1 = New Socket As "Server"
' Si connette al proprgramma "Server" impostando l'indirizzo IP privato e il numero della porta del "Server" medesimo:
 SockClient1.Connect("Indirizzo_IP_privato", 12345)
 
 Do While (SockClient1.Status <> 7) And (SockClient1.Status > 0)
   Wait 0.01
 Loop
 
 If SockClient1.Status <> 7 Then
   Print "\e[31mErrore !\e[0m"
   SockClient1.Close
   Quit
 Endif
 
End

Public Sub Button2_Click()
 
' Invia testo al Server, affinché lo indirizzi all'altro programma "Client":
 Write #SockClient1, TextArea1.Text
 
End

Public Sub Server_Read()   ' Legge i dati inviati dal Server
 
 Dim buf As String
 
 Read #SockClient1, buf, Lof(SockClient1)
 
 With TextArea1
   .Wrap = True
   .Text = buf & gb.NewLine
   .SetFocus
 End With
 
End

Public Sub TextArea1_MouseUp()
 
 TextArea1.Clear

End


Il codice del secondo "Client Socket" sarà uguale al codice del primo "Client Socket".


Note

[1] Da vedere le seguenti pagine web:
- http://gambaswiki.org/wiki/doc/network
- http://gambaswiki.org/wiki/comp/gb.net/serversocket
- http://gambaswiki.org/wiki/comp/gb.net/socket
- http://captainbodgit.blogspot.com/2016/08/using-sockets-with-gambas.html
- https://jsbsan.blogspot.com/2012/07/arduino-y-linux-ejemplo-de-uso-de.html
- https://docs.oracle.com/cd/E19620-01/805-4041/index.html
- http://linuxdidattica.org/docs/altre_scuole/planck/socket/progr-socket.pdf
- https://www.wikihow.it/Controllare-l%27Indirizzo-IP-su-Linux
- https://noviello.it/come-trovare-il-proprio-indirizzo-ip-su-linux/
- https://linuxiano.altervista.org/2019/11/indirizzo-ip-dal-terminale-linux/