Nochmal für alle: TCP Beispiel

    • VB.NET

    Es gibt 7 Antworten in diesem Thema. Der letzte Beitrag () ist von Malischh.

      Nochmal für alle: TCP Beispiel

      Da ich in den letzten Threads ziemlich oft gefragt wurde, wie man einen TCP Server / Client schreibt, werd ich jetzt 2 Beispiele angeben.


      TCP Listener. Läuft hier auf einer Konsole.
      Da sich dieses bsp in einer Form aufhängt, hier der Link für eine Form: tutorials.de/forum/visual-basi…12633-winsock-vb-tcp.html
      gpwiki.org/index.php/VBNET:Sockets

      Besser ist es aber wenn man einfach den code unten mit einem Thread ausführt, dass führt zu keinem absturz...


      VB.NET-Quellcode

      1. Imports System
      2. Imports System.IO
      3. Imports System.Net
      4. Imports System.Net.Sockets
      5. Imports System.Text
      6. Imports Microsoft.VisualBasic
      7. Class MyTcpListener
      8. Sub Main()
      9. Console.WriteLine("Bitte geben sie die Locale IP ein: ")
      10. connect(Console.ReadLine())
      11. End Sub
      12. Sub connect(ByVal ip As String)
      13. Dim server As TcpListener
      14. server = Nothing
      15. Try
      16. ' Set the TcpListener on port 13000.
      17. Dim port As Int32 = 1234
      18. Dim localAddr As IPAddress = IPAddress.Parse(ip)
      19. server = New TcpListener(localAddr, port)
      20. ' Start listening for client requests.
      21. server.Start()
      22. ' Buffer for reading data
      23. Dim bytes(1024) As Byte
      24. Dim data As String = Nothing
      25. ' Enter the listening loop.
      26. While True
      27. Console.Write("Waiting for a connection... ")
      28. ' Perform a blocking call to accept requests.
      29. ' You could also user server.AcceptSocket() here.
      30. Dim client As TcpClient = server.AcceptTcpClient()
      31. Console.WriteLine("Connected!")
      32. data = Nothing
      33. ' Get a stream object for reading and writing
      34. Dim stream As NetworkStream = client.GetStream()
      35. Dim i As Int32
      36. ' Loop to receive all the data sent by the client.
      37. i = stream.Read(bytes, 0, bytes.Length)
      38. While (i <> 0)
      39. ' Translate data bytes to a ASCII string.
      40. data = System.Text.Encoding.ASCII.GetString(bytes, 0, i)
      41. Console.WriteLine("Received: {0}", data)
      42. ' Hier hast du den empfangenen string data
      43. If data = ....
      44. 'Anschließend gibst du die antwort:
      45. data = "Button1.text = hehehe"
      46. Dim msg As Byte() = System.Text.Encoding.ASCII.GetBytes(data)
      47. stream.Write(msg, 0, msg.Length)
      48. Console.WriteLine("Sent: {0}", data)
      49. i = stream.Read(bytes, 0, bytes.Length)
      50. End While
      51. ' Shutdown and end connection
      52. client.Close()
      53. End While
      54. Catch e As SocketException
      55. Console.WriteLine("SocketException: {0}", e)
      56. Finally
      57. server.Stop()
      58. End Try
      59. Console.WriteLine(ControlChars.Cr + "Hit enter to continue....")
      60. Console.Read()
      61. End Sub
      62. End Class 'MyTcpListener












      Und hier der dazugehörige TCP Client. Hier: Für Konsole läuft aber genauso für eine Form.


      VB.NET-Quellcode

      1. Imports System
      2. Imports System.IO
      3. Imports System.Net
      4. Imports System.Net.Sockets
      5. Class MyTcpListener
      6. Sub Main()
      7. Console.WriteLine("Bitte geben sie die IP des Servers ein: ")
      8. Dim temp As String = Console.ReadLine
      9. Console.WriteLine("Bitte die Nachricht eingeben: ")
      10. Connect(temp, Console.ReadLine)
      11. End Sub
      12. Sub Connect(ByVal server As [String], ByVal message As [String])
      13. Try
      14. ' Create a TcpClient.
      15. ' Note, for this client to work you need to have a TcpServer
      16. ' connected to the same address as specified by the server, port
      17. ' combination.
      18. Dim port As Int32 = 1234
      19. Dim client As New TcpClient(server, port)
      20. ' Translate the passed message into ASCII and store it as a Byte array.
      21. Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(message)
      22. ' Get a client stream for reading and writing.
      23. ' Stream stream = client.GetStream();
      24. Dim stream As NetworkStream = client.GetStream()
      25. ' Send the message to the connected TcpServer.
      26. stream.Write(data, 0, data.Length)
      27. Console.WriteLine("Sent: {0}", message)
      28. ' Receive the TcpServer.response.
      29. ' Buffer to store the response bytes.
      30. data = New [Byte](256) {}
      31. ' String to store the response ASCII representation.
      32. Dim responseData As [String] = [String].Empty
      33. ' Read the first batch of the TcpServer response bytes.
      34. Dim bytes As Int32 = stream.Read(data, 0, data.Length)
      35. responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
      36. Console.WriteLine("Received: {0}", responseData)
      37. ' Close everything.
      38. stream.Close()
      39. client.Close()
      40. Catch e As ArgumentNullException
      41. Console.WriteLine("ArgumentNullException: {0}", e)
      42. Catch e As SocketException
      43. Console.WriteLine("SocketException: {0}", e)
      44. End Try
      45. Console.WriteLine(ControlChars.Cr + " Press Enter to continue...")
      46. Console.Read()
      47. End Sub 'Connect
      48. End Class 'MyTcpListener



      Ich hoff das mein Thread euch weiter hilft! :thumbup: :thumbsup:

      *Topic verschoben, passt gut hierher*

      Dieser Beitrag wurde bereits 5 mal editiert, zuletzt von „Malischh“ ()

      Hier noch für die Vollständigkeit:

      UDP Client!:

      VB.NET-Quellcode

      1. ' This constructor arbitrarily assigns the local port number.
      2. Dim udpClient As New UdpClient(11000)
      3. Try
      4. udpClient.Connect("www.contoso.com", 11000)
      5. ' Sends a message to the host to which you have connected.
      6. Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("Is anybody there?")
      7. udpClient.Send(sendBytes, sendBytes.Length)
      8. ' Sends message to a different host using optional hostname and port parameters.
      9. Dim udpClientB As New UdpClient()
      10. udpClientB.Send(sendBytes, sendBytes.Length, "AlternateHostMachineName", 11000)
      11. ' IPEndPoint object will allow us to read datagrams sent from any source.
      12. Dim RemoteIpEndPoint As New IPEndPoint(IPAddress.Any, 0)
      13. ' UdpClient.Receive blocks until a message is received from a remote host.
      14. Dim receiveBytes As [Byte]() = udpClient.Receive(RemoteIpEndPoint)
      15. Dim returnData As String = Encoding.ASCII.GetString(receiveBytes)
      16. ' Which one of these two hosts responded?
      17. Console.WriteLine(("This is the message you received " + _
      18. returnData.ToString()))
      19. Console.WriteLine(("This message was sent from " + _
      20. RemoteIpEndPoint.Address.ToString() + _
      21. " on their port number " + _
      22. RemoteIpEndPoint.Port.ToString()))
      23. udpClient.Close()
      24. udpClientB.Close()
      25. Catch e As Exception
      26. Console.WriteLine(e.ToString())
      27. End Try
      28. End Sub



      Den habe ich aber nicht angepasst, also muss da noch ein bisschen gemacht werden.


      Ach ja, fals jemand einen guten Beispiel Code für einen UDP Listener hat, bitte Posten, da ich noch keinen richtigen Code gefunden habe, dass der UDP Listener in einer Schleife auf Verbindungen wartet! So ungefähr wie im obigen TCP Listener Beispiel. THX :thumbsup:

      Enjoy^^
      Da man schwer ein gutes Tutorial für einen UDP Listener findet, werd ich jetzt mal ein Beispiel dazu machen:

      VB.NET-Quellcode

      1. Imports System.Threading
      2. Imports System.Net.Sockets
      3. Imports System.IO
      4. Imports System.Net
      5. Public Class MainClass
      6. Shared client As UdpClient
      7. Shared receivePoint As IPEndPoint
      8. Public Shared Sub Main()
      9. client = New UdpClient(5000)
      10. receivePoint = New IPEndPoint(New IPAddress(0), 1234)
      11. Dim readThread As Thread = New Thread(New ThreadStart(AddressOf WaitForPackets))
      12. readThread.Start() ' wait for packets
      13. End Sub
      14. Public Shared Sub WaitForPackets()
      15. While True
      16. Dim data As Byte() = client.Receive(receivePoint)
      17. Dim rev As String = System.Text.Encoding.ASCII.GetString(data)
      18. MsgBox(rev)
      19. client.Send(data, data.Length, receivePoint)
      20. End While
      21. End Sub
      22. End Class




      PS.: Meine Codes sind alle getestet!



      Edit: man hätte alles auch mit einem Simplen Stream machen können. Erspart Viel Arbeit und istübersichtlicher^^

      Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von „Malischh“ ()

      ---------------------------
      ConsoleApplication1
      ---------------------------
      Es konnte keine Verbindung hergestellt werden, da der Zielcomputer die Verbindung verweigerte 62.143.130.191:1234
      ---------------------------
      OK
      ---------------------------

      ... was muss ich machen? Ich dachte sowieso man muss irgendwie die Anfrage akzeptieren bevor die Verbindung zustande kommen kann...