1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| Private Sub Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
LoadConfigXml()
If mode = "server" Then
SocketListen()
Else
ConnectToServer()
Timer1.Start()
End If
End Sub
' charge le fichier de configuration
Private Sub LoadConfigXml()
Dim xDoc As XmlDocument = New XmlDocument()
xDoc.Load(My.Application.Info.DirectoryPath + "\config.xml")
Dim root As XmlElement = xDoc.DocumentElement
mode = root.GetAttribute("mode")
ipServer = IPAddress.Parse(root.GetAttribute("ipserver"))
End Sub
' mode serveur
Private Sub SocketListen()
socketServer = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
socketServer.Bind(New IPEndPoint(ipServer, 15))
socketServer.Listen(500)
socketServer.BeginAccept(New AsyncCallback(AddressOf connexionAcceptCallback), socketServer)
End Sub
Private Sub ReceiveCallback(ByVal asyncResult As IAsyncResult)
Debug.WriteLine("réception")
Dim read As Integer = socketClient.EndReceive(asyncResult)
End Sub
Private Sub connexionAcceptCallback(ByVal asyncResult As IAsyncResult)
socketServer.BeginReceive(tempBuffer, 0, tempBuffer.Length, SocketFlags.None, AddressOf ReceiveCallback, socketClient)
socketClient = socketServer.EndAccept(asyncResult)
Debug.WriteLine("connexion acceptée")
End Sub
' mode client
Private Sub ConnectToServer()
socketClient = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
socketClient.BeginConnect(New IPEndPoint(ipServer, 15), AddressOf ConnexionConnectCallback, socketClient)
End Sub
Private Sub ConnexionConnectCallback(ByVal asyncResult As IAsyncResult)
socketClient.EndConnect(asyncResult)
End Sub
' test envoie message
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim buff As Byte() = System.Text.Encoding.ASCII.GetBytes("test")
socketClient.BeginSend(buff, 0, buff.Length, SocketFlags.None, AddressOf SendCallback, socketClient)
End Sub
Private Sub SendCallback(ByVal asyncResult As IAsyncResult)
Dim send As Integer = socketClient.EndSend(asyncResult)
End Sub |
Partager