TCP File Transfer

    • VB.NET

    Es gibt 3 Antworten in diesem Thema. Der letzte Beitrag () ist von xored.

      TCP File Transfer

      Moin,

      habe hier mal ne ganz simple Methode für euch um via TCP Dateien auszutauschen. Ist natürlich noch sehr ausbaufähig.



      Server:

      VB.NET-Quellcode

      1. Imports System.Net.Sockets
      2. Imports System.IO
      3. Imports System.Net
      4. Imports System.Text.RegularExpressions
      5. Imports System.Drawing
      6. Imports System.Text
      7. Imports System.Windows.Forms
      8. Public Class xoredServer
      9. Public Port As Integer = 8000
      10. Public MaxFileSize As Integer = 1398104 'Das ist keine Größeneinheit, sondern die Länge des Strings, in welche die Datei umgewandelt wird
      11. Private list As New List(Of Connection)
      12. Dim Streamer As String = "..."
      13. Dim LvUserWithIp As New ListView
      14. Private server As TcpListener
      15. Private client As New TcpClient
      16. Private ipendpoint As IPEndPoint = New IPEndPoint(IPAddress.Any, Port)
      17. Private Structure Connection
      18. Dim stream As NetworkStream
      19. Dim streamw As StreamWriter
      20. Dim streamr As StreamReader
      21. Dim IP As String
      22. End Structure
      23. ''' <summary>
      24. ''' Die Funktion sendet einen String an alle verbundenen Clients
      25. ''' </summary>
      26. Private Sub SendPacket(ByVal s As String)
      27. For Each c As Connection In list
      28. Try
      29. c.streamw.WriteLine(s)
      30. c.streamw.Flush()
      31. Catch
      32. End Try
      33. Next
      34. End Sub
      35. Private Sub SendPrivatePacket(ByVal s As String, ByVal IP As String)
      36. For Each c As Connection In list
      37. Try
      38. If c.IP = IP Then
      39. c.streamw.WriteLine(s)
      40. c.streamw.Flush()
      41. End If
      42. Catch
      43. End Try
      44. Next
      45. End Sub
      46. Public Function StartServer() As Object
      47. Console.ForegroundColor = ConsoleColor.Cyan
      48. Console.WriteLine("Server has been started...")
      49. Console.WriteLine("--------------------------------------------------------------------")
      50. server = New TcpListener(ipendpoint)
      51. server.Start()
      52. While True
      53. client = server.AcceptTcpClient
      54. Dim Connection As New Connection
      55. Connection.stream = client.GetStream
      56. Connection.streamr = New StreamReader(Connection.stream)
      57. Connection.streamw = New StreamWriter(Connection.stream)
      58. Connection.IP = (IPAddress.Parse(CType(client.Client.RemoteEndPoint, IPEndPoint).Address.ToString())).ToString()
      59. list.Add(Connection)
      60. Console.ForegroundColor = ConsoleColor.Green
      61. Console.WriteLine(Connection.IP & ": Received connection")
      62. Console.WriteLine("--------------------------------------------------------------------")
      63. Console.ResetColor()
      64. Dim ListenToConnectionThread As New Threading.Thread(AddressOf ListenToConnection)
      65. ListenToConnectionThread.Start(Connection)
      66. End While
      67. End Function
      68. Private Sub ListenToConnection(ByVal con As Connection)
      69. Do
      70. Try
      71. Dim ipend As String = (IPAddress.Parse(CType(client.Client.RemoteEndPoint, IPEndPoint).Address.ToString())).ToString()
      72. Dim tmp As String = con.streamr.ReadLine
      73. Try
      74. ''''
      75. '''' /SendFile Sender File FileName
      76. '''' Hier wird eine vom Client gesendete Datei angenommen und gespeichert
      77. ''''
      78. If tmp.Contains("/SendFile") Then
      79. Console.WriteLine(ipend & ": Recv SendFilePacket by (see logfile)")
      80. Dim str() = {tmp}
      81. For Each Word In str
      82. Dim regx = New Regex(" +")
      83. Dim splitString = regx.Split(Word)
      84. Dim BaseFile As String = (splitString(1))
      85. Dim FileName As String = (splitString(2))
      86. FileName = FileName.Replace("[+1]", " ")
      87. Console.WriteLine(ipend & ": Recvd File")
      88. If (splitString(1).Length < MaxFileSize) Then
      89. If Not (My.Computer.FileSystem.FileExists(My.Computer.FileSystem.CurrentDirectory & "\Files\" & FileName & ".txt")) Then
      90. Dim objWriter As New System.IO.StreamWriter(My.Computer.FileSystem.CurrentDirectory & "\Files\" & FileName & ".txt")
      91. objWriter.Write(BaseFile)
      92. objWriter.Close()
      93. SendPrivatePacket("/FileAccepted", ipend)
      94. Console.WriteLine(ipend & ": FileAccepted")
      95. Dim FileList As String = ""
      96. Dim dir As New DirectoryInfo(My.Computer.FileSystem.CurrentDirectory & "\Files\")
      97. For Each f In dir.GetFiles()
      98. FileList = FileList & "[~1]" & f.Name & "[+1]"
      99. Next
      100. SendPrivatePacket("/SendFileListToClient" & " " & FileList, ipend)
      101. Else
      102. SendPrivatePacket("/FileAlreadyExist", ipend)
      103. Console.WriteLine(ipend & ": File does already exist")
      104. End If
      105. End If
      106. Console.WriteLine("--------------------------------------------------------------------")
      107. Next
      108. End If
      109. ''''
      110. '''' /RequestFile RequestedFile TargetUser
      111. '''' Hier wird eine angeforderte Datei an den Client gesendet
      112. ''''
      113. If tmp.Contains("/RequestUpload") Then
      114. Console.WriteLine(ipend & ": Recv RequestUploadPacket")
      115. Dim str() = {tmp}
      116. For Each Word In str
      117. Dim regx = New Regex(" +")
      118. Dim splitString = regx.Split(Word)
      119. Console.WriteLine(ipend & ": RecvFile:" & splitString(1))
      120. Try
      121. Dim fileReader As String
      122. fileReader = My.Computer.FileSystem.ReadAllText(My.Computer.FileSystem.CurrentDirectory & "\Files\" & splitString(1) & ".txt")
      123. SendPrivatePacket("/SendFileToClient" & " " & fileReader, ipend)
      124. Catch
      125. End Try
      126. Console.WriteLine("--------------------------------------------------------------------")
      127. Next
      128. End If
      129. ''''
      130. '''' /RequestFileList
      131. '''' Hier wird der FilesOrdner-Inhalt an den Client gesendet
      132. ''''
      133. If tmp.Contains("/RequestFileList") Then
      134. Console.WriteLine(ipend & ": Recv RequestFileListPacket")
      135. Dim str() = {tmp}
      136. For Each Word In str
      137. Dim regx = New Regex(" +")
      138. Dim splitString = regx.Split(Word)
      139. Dim FileList As String = ""
      140. Dim dir As New DirectoryInfo(My.Computer.FileSystem.CurrentDirectory & "\Files\")
      141. For Each f In dir.GetFiles()
      142. FileList = FileList & "[~1]" & f.Name & "[+1]"
      143. Next
      144. SendPrivatePacket("/SendFileListToClient" & " " & FileList, ipend)
      145. Next
      146. Console.WriteLine("--------------------------------------------------------------------")
      147. End If
      148. Catch
      149. End Try
      150. Catch
      151. Try
      152. Dim ipend As String = (IPAddress.Parse(CType(client.Client.RemoteEndPoint, IPEndPoint).Address.ToString())).ToString()
      153. list.Remove(con)
      154. con.stream.Close()
      155. con.stream.Dispose()
      156. con.streamw.Close()
      157. con.streamw.Dispose()
      158. con.streamr.Close()
      159. con.streamr.Dispose()
      160. Console.ForegroundColor = ConsoleColor.Red
      161. Console.WriteLine(ipend & ": lost connection.")
      162. Console.WriteLine("--------------------------------------------------------------------")
      163. Console.ResetColor()
      164. Catch
      165. End Try
      166. Exit Do
      167. End Try
      168. Loop
      169. End Sub
      170. End Class


      So startet ihr den Server:

      VB.NET-Quellcode

      1. Module Server
      2. Sub Main()
      3. Dim xoredTCP As xoredServer = New xoredServer()
      4. xoredTCP.Port = 8000
      5. xoredTCP.StartServer()
      6. End Sub
      7. End Module


      Ihr könnt natürlich auch euren bereits vorhandenen Server benutzen und mit diesem Modul erweitern.

      Client:

      VB.NET-Quellcode

      1. Option Strict On
      2. Imports System.IO
      3. Imports System.Net.Sockets
      4. Imports System.Text.RegularExpressions
      5. Public Class Form1
      6. Public stream As NetworkStream
      7. Public streamw As StreamWriter
      8. Public streamr As StreamReader
      9. Public client As New TcpClient
      10. Public Delegate Sub DAddItem(ByVal s As String)
      11. Public ListenThread As New Threading.Thread(AddressOf Listen)
      12. Public Sub Listen()
      13. While client.Connected
      14. Try
      15. Me.Invoke(New DAddItem(AddressOf AddItem), streamr.ReadLine)
      16. Catch
      17. Application.Exit()
      18. End Try
      19. End While
      20. End Sub
      21. Public Function ConvertFileToBase64(ByVal fileName As String) As String
      22. Return Convert.ToBase64String(System.IO.File.ReadAllBytes(fileName))
      23. End Function
      24. Public Sub AddItem(ByVal s As String)
      25. If Not s Is Nothing Then
      26. If (s.Contains("/FileAccepted")) Then 'Ändern
      27. MsgBox("File successfully uploaded!", MsgBoxStyle.Information)
      28. End If
      29. If (s.Contains("/FileAlreadyExist")) Then 'Ändern
      30. MsgBox("This file does already exist!", MsgBoxStyle.Exclamation)
      31. ' MsgBox("test")
      32. End If
      33. If (s.Contains("/SendFileListToClient")) Then
      34. Dim str() = {s}
      35. For Each sx In str
      36. Dim regx = New Regex(" +")
      37. Dim splitString = regx.Split(s)
      38. Dim List As String = (splitString(1))
      39. Dim ListConvert As New List(Of String)()
      40. ListConvert.Clear()
      41. lvFiles.Items.Clear() 'Ändern
      42. List = List.Replace("[+1]", vbNewLine)
      43. List = List.Replace("[~1]", "")
      44. Dim Ar() As String = Split(List, Environment.NewLine)
      45. For Each Eintrag As String In Ar
      46. ListConvert.Add(Eintrag)
      47. Next
      48. For Each val As String In ListConvert
      49. If Not (String.IsNullOrEmpty(val)) Then
      50. Dim LW As New ListViewItem
      51. LW.Text = val.Substring(0, val.Length - 4)
      52. If (val.Substring(0, val.Length - 4).Substring(Math.Max(0, val.Substring(0, val.Length - 4).Length - 4)) = ".exe") Then
      53. LW.ImageIndex = 0
      54. ElseIf (val.Substring(0, val.Length - 4).Substring(Math.Max(0, val.Substring(0, val.Length - 4).Length - 5)) = ".html") Then
      55. LW.ImageIndex = 1
      56. ElseIf (val.Substring(0, val.Length - 4).Substring(Math.Max(0, val.Substring(0, val.Length - 4).Length - 4)) = ".php") Then
      57. LW.ImageIndex = 2
      58. ElseIf (val.Substring(0, val.Length - 4).Substring(Math.Max(0, val.Substring(0, val.Length - 4).Length - 4)) = ".txt") Then
      59. LW.ImageIndex = 3
      60. ElseIf (val.Substring(0, val.Length - 4).Substring(Math.Max(0, val.Substring(0, val.Length - 4).Length - 4)) = ".mp4") Then
      61. LW.ImageIndex = 4
      62. ElseIf (val.Substring(0, val.Length - 4).Substring(Math.Max(0, val.Substring(0, val.Length - 4).Length - 4)) = ".jpg") Then
      63. LW.ImageIndex = 6
      64. ElseIf (val.Substring(0, val.Length - 4).Substring(Math.Max(0, val.Substring(0, val.Length - 4).Length - 5)) = ".jpeg") Then
      65. LW.ImageIndex = 6
      66. ElseIf (val.Substring(0, val.Length - 4).Substring(Math.Max(0, val.Substring(0, val.Length - 4).Length - 4)) = ".png") Then
      67. LW.ImageIndex = 7
      68. Else
      69. LW.ImageIndex = 5
      70. End If
      71. lvFiles.Items.Add(LW) 'Ändern
      72. End If
      73. Next
      74. Next
      75. End If
      76. If (s.Contains("/SendFileToClient")) Then
      77. Dim str() = {s}
      78. For Each sx In str
      79. Dim regx = New Regex(" +")
      80. Dim splitString = regx.Split(s)
      81. Dim BaseFile As String = splitString(1)
      82. If Not My.Computer.FileSystem.FileExists(My.Computer.FileSystem.CurrentDirectory & "\Files\" & lvFiles.SelectedItems(0).SubItems(0).Text) Then 'Ändern
      83. Dim bytes() As Byte
      84. bytes = System.Convert.FromBase64String(BaseFile)
      85. Dim writer As New System.IO.BinaryWriter(IO.File.Open(My.Computer.FileSystem.CurrentDirectory & "\Files\" & lvFiles.SelectedItems(0).SubItems(0).Text, IO.FileMode.Create)) 'Ändern
      86. writer.Write(bytes)
      87. writer.Close()
      88. MsgBox("File successfully downloaded!", MsgBoxStyle.Information)
      89. End If
      90. Next
      91. End If
      92. End If
      93. End Sub
      94. Public Function ConnectToServer() As Object
      95. Try
      96. client.Connect("127.0.0.1", 8000)
      97. If client.Connected Then
      98. stream = client.GetStream
      99. streamw = New StreamWriter(stream)
      100. streamr = New StreamReader(stream)
      101. ListenThread.Start()
      102. Else
      103. MsgBox("The server is not reachable!", MsgBoxStyle.Exclamation)
      104. Application.Exit()
      105. End If
      106. Catch ex As Exception
      107. MsgBox("The server is not reachable!", MsgBoxStyle.Exclamation)
      108. Application.Exit()
      109. End Try
      110. End Function
      111. Public Function SendPacket(ByVal Content As String) As Object
      112. streamw.WriteLine(Content)
      113. streamw.Flush()
      114. End Function
      115. Public Function RequestFileList() As Object
      116. SendPacket("/RequestFileList")
      117. End Function
      118. Public Function DownloadFile(ByVal Filename As String) As Object
      119. SendPacket("/RequestUpload " & Filename)
      120. End Function
      121. Public Function SendFile(ByVal Basefile As String, ByVal Filename As String) As Object
      122. SendPacket("/SendFile " & Basefile & " " & Filename)
      123. End Function
      124. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnDownload.Click
      125. DownloadFile(lvFiles.SelectedItems.Item(0).SubItems(0).Text)
      126. End Sub
      127. Private Sub Button2_Click(sender As Object, e As EventArgs) Handles btnUpload.Click
      128. Dim ofd As New OpenFileDialog
      129. If (ofd.ShowDialog() = DialogResult.OK) Then
      130. Dim SelectedFileWithPath As String
      131. Dim FileName As String = System.IO.Path.GetFileName(ofd.FileName)
      132. Dim BaseFile As String = ""
      133. SelectedFileWithPath = ofd.FileName
      134. SelectedFileWithPath = SelectedFileWithPath.Replace(" ", "[+1]")
      135. BaseFile = ConvertFileToBase64(ofd.FileName)
      136. If (BaseFile.Length < 1398104) Then
      137. SendFile(BaseFile, FileName)
      138. Else
      139. MsgBox("This file is too large!", MsgBoxStyle.Exclamation)
      140. End If
      141. End If
      142. End Sub
      143. Private Sub Button3_Click(sender As Object, e As EventArgs) Handles btnAktualisieren.Click
      144. RequestFileList()
      145. End Sub
      146. Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      147. ConnectToServer()
      148. End Sub
      149. End Class


      Ich hoffe die Formatierung klappt bei der Menge an Zeichen noch.
      Beispiel-Projekt findet ihr im Anhang.
      Ist mit Sicherheit nicht der schönste Code, aber er klappt und dient lediglich zur Inspiration. Dafür mit Liebe geschrieben :)

      Verweise auf die Icon-Ersteller:
      flaticon.com/authors/smashicons
      freepik.com
      flaticon.com/authors/dimitry-miroliubov
      Dateien


      Meine Website:
      www.renebischof.de

      Meine erste App (Android):
      PartyPalooza

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

      Kurzer Nachtrag, da der Hauptpost sonst zu unübersichtlich wird.
      Es gibt eine bessere Methode als meine um die maximale Dateigröße zu definieren.

      Ich bin mir gerade bloß nicht sicher ob 1000, oder 1024.

      VB.NET-Quellcode

      1. Public Enum SizeTypes
      2. KB
      3. MB
      4. GB
      5. End Enum
      6. Public Function GetFileSizeByBase64(ByVal Base64Input As String, ByVal SizeType As SizeTypes) As Integer
      7. If (SizeType = SizeTypes.KB) Then
      8. Return (Base64Input.Length * (3 / 4) - 1) / 1000 'Returned die KB der Datei
      9. End If
      10. If (SizeType = SizeTypes.MB) Then
      11. Return (Base64Input.Length * (3 / 4) - 1) / 1000 / 1000 'Returned die MB der Datei
      12. End If
      13. If (SizeType = SizeTypes.GB) Then
      14. Return (Base64Input.Length * (3 / 4) - 1) / 1000 / 1000 / 1000 'Returned die GB der Datei
      15. End If
      16. End Function



      Und dann eben statt:

      VB.NET-Quellcode

      1. If (Basefile.Length < MaxFileSize) Then


      VB.NET-Quellcode

      1. If (GetFileSizeByBase64(BaseFile, SizeTypes.MB) < MaxFileSize) Then


      MaxFileSize muss dann dementsprechend definiert werden. Gruß


      Meine Website:
      www.renebischof.de

      Meine erste App (Android):
      PartyPalooza
      @xored Machst Du zunächst Option Strict On.
      Visual Studio - Empfohlene Einstellungen
      Falls Du diesen Code kopierst, achte auf die C&P-Bremse.
      Jede einzelne Zeile Deines Programms, die Du nicht explizit getestet hast, ist falsch :!:
      Ein guter .NET-Snippetkonverter (der ist verfügbar).
      Programmierfragen über PN / Konversation werden ignoriert!