Moin,
habe hier mal ne ganz simple Methode für euch um via TCP Dateien auszutauschen. Ist natürlich noch sehr ausbaufähig.
Server:
So startet ihr den Server:
Ihr könnt natürlich auch euren bereits vorhandenen Server benutzen und mit diesem Modul erweitern.
Client:
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
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
- Imports System.Net.Sockets
- Imports System.IO
- Imports System.Net
- Imports System.Text.RegularExpressions
- Imports System.Drawing
- Imports System.Text
- Imports System.Windows.Forms
- Public Class xoredServer
- Public Port As Integer = 8000
- Public MaxFileSize As Integer = 1398104 'Das ist keine Größeneinheit, sondern die Länge des Strings, in welche die Datei umgewandelt wird
- Private list As New List(Of Connection)
- Dim Streamer As String = "..."
- Dim LvUserWithIp As New ListView
- Private server As TcpListener
- Private client As New TcpClient
- Private ipendpoint As IPEndPoint = New IPEndPoint(IPAddress.Any, Port)
- Private Structure Connection
- Dim stream As NetworkStream
- Dim streamw As StreamWriter
- Dim streamr As StreamReader
- Dim IP As String
- End Structure
- ''' <summary>
- ''' Die Funktion sendet einen String an alle verbundenen Clients
- ''' </summary>
- Private Sub SendPacket(ByVal s As String)
- For Each c As Connection In list
- Try
- c.streamw.WriteLine(s)
- c.streamw.Flush()
- Catch
- End Try
- Next
- End Sub
- Private Sub SendPrivatePacket(ByVal s As String, ByVal IP As String)
- For Each c As Connection In list
- Try
- If c.IP = IP Then
- c.streamw.WriteLine(s)
- c.streamw.Flush()
- End If
- Catch
- End Try
- Next
- End Sub
- Public Function StartServer() As Object
- Console.ForegroundColor = ConsoleColor.Cyan
- Console.WriteLine("Server has been started...")
- Console.WriteLine("--------------------------------------------------------------------")
- server = New TcpListener(ipendpoint)
- server.Start()
- While True
- client = server.AcceptTcpClient
- Dim Connection As New Connection
- Connection.stream = client.GetStream
- Connection.streamr = New StreamReader(Connection.stream)
- Connection.streamw = New StreamWriter(Connection.stream)
- Connection.IP = (IPAddress.Parse(CType(client.Client.RemoteEndPoint, IPEndPoint).Address.ToString())).ToString()
- list.Add(Connection)
- Console.ForegroundColor = ConsoleColor.Green
- Console.WriteLine(Connection.IP & ": Received connection")
- Console.WriteLine("--------------------------------------------------------------------")
- Console.ResetColor()
- Dim ListenToConnectionThread As New Threading.Thread(AddressOf ListenToConnection)
- ListenToConnectionThread.Start(Connection)
- End While
- End Function
- Private Sub ListenToConnection(ByVal con As Connection)
- Do
- Try
- Dim ipend As String = (IPAddress.Parse(CType(client.Client.RemoteEndPoint, IPEndPoint).Address.ToString())).ToString()
- Dim tmp As String = con.streamr.ReadLine
- Try
- ''''
- '''' /SendFile Sender File FileName
- '''' Hier wird eine vom Client gesendete Datei angenommen und gespeichert
- ''''
- If tmp.Contains("/SendFile") Then
- Console.WriteLine(ipend & ": Recv SendFilePacket by (see logfile)")
- Dim str() = {tmp}
- For Each Word In str
- Dim regx = New Regex(" +")
- Dim splitString = regx.Split(Word)
- Dim BaseFile As String = (splitString(1))
- Dim FileName As String = (splitString(2))
- FileName = FileName.Replace("[+1]", " ")
- Console.WriteLine(ipend & ": Recvd File")
- If (splitString(1).Length < MaxFileSize) Then
- If Not (My.Computer.FileSystem.FileExists(My.Computer.FileSystem.CurrentDirectory & "\Files\" & FileName & ".txt")) Then
- Dim objWriter As New System.IO.StreamWriter(My.Computer.FileSystem.CurrentDirectory & "\Files\" & FileName & ".txt")
- objWriter.Write(BaseFile)
- objWriter.Close()
- SendPrivatePacket("/FileAccepted", ipend)
- Console.WriteLine(ipend & ": FileAccepted")
- Dim FileList As String = ""
- Dim dir As New DirectoryInfo(My.Computer.FileSystem.CurrentDirectory & "\Files\")
- For Each f In dir.GetFiles()
- FileList = FileList & "[~1]" & f.Name & "[+1]"
- Next
- SendPrivatePacket("/SendFileListToClient" & " " & FileList, ipend)
- Else
- SendPrivatePacket("/FileAlreadyExist", ipend)
- Console.WriteLine(ipend & ": File does already exist")
- End If
- End If
- Console.WriteLine("--------------------------------------------------------------------")
- Next
- End If
- ''''
- '''' /RequestFile RequestedFile TargetUser
- '''' Hier wird eine angeforderte Datei an den Client gesendet
- ''''
- If tmp.Contains("/RequestUpload") Then
- Console.WriteLine(ipend & ": Recv RequestUploadPacket")
- Dim str() = {tmp}
- For Each Word In str
- Dim regx = New Regex(" +")
- Dim splitString = regx.Split(Word)
- Console.WriteLine(ipend & ": RecvFile:" & splitString(1))
- Try
- Dim fileReader As String
- fileReader = My.Computer.FileSystem.ReadAllText(My.Computer.FileSystem.CurrentDirectory & "\Files\" & splitString(1) & ".txt")
- SendPrivatePacket("/SendFileToClient" & " " & fileReader, ipend)
- Catch
- End Try
- Console.WriteLine("--------------------------------------------------------------------")
- Next
- End If
- ''''
- '''' /RequestFileList
- '''' Hier wird der FilesOrdner-Inhalt an den Client gesendet
- ''''
- If tmp.Contains("/RequestFileList") Then
- Console.WriteLine(ipend & ": Recv RequestFileListPacket")
- Dim str() = {tmp}
- For Each Word In str
- Dim regx = New Regex(" +")
- Dim splitString = regx.Split(Word)
- Dim FileList As String = ""
- Dim dir As New DirectoryInfo(My.Computer.FileSystem.CurrentDirectory & "\Files\")
- For Each f In dir.GetFiles()
- FileList = FileList & "[~1]" & f.Name & "[+1]"
- Next
- SendPrivatePacket("/SendFileListToClient" & " " & FileList, ipend)
- Next
- Console.WriteLine("--------------------------------------------------------------------")
- End If
- Catch
- End Try
- Catch
- Try
- Dim ipend As String = (IPAddress.Parse(CType(client.Client.RemoteEndPoint, IPEndPoint).Address.ToString())).ToString()
- list.Remove(con)
- con.stream.Close()
- con.stream.Dispose()
- con.streamw.Close()
- con.streamw.Dispose()
- con.streamr.Close()
- con.streamr.Dispose()
- Console.ForegroundColor = ConsoleColor.Red
- Console.WriteLine(ipend & ": lost connection.")
- Console.WriteLine("--------------------------------------------------------------------")
- Console.ResetColor()
- Catch
- End Try
- Exit Do
- End Try
- Loop
- End Sub
- End Class
So startet ihr den Server:
Ihr könnt natürlich auch euren bereits vorhandenen Server benutzen und mit diesem Modul erweitern.
Client:
VB.NET-Quellcode
- Option Strict On
- Imports System.IO
- Imports System.Net.Sockets
- Imports System.Text.RegularExpressions
- Public Class Form1
- Public stream As NetworkStream
- Public streamw As StreamWriter
- Public streamr As StreamReader
- Public client As New TcpClient
- Public Delegate Sub DAddItem(ByVal s As String)
- Public ListenThread As New Threading.Thread(AddressOf Listen)
- Public Sub Listen()
- While client.Connected
- Try
- Me.Invoke(New DAddItem(AddressOf AddItem), streamr.ReadLine)
- Catch
- Application.Exit()
- End Try
- End While
- End Sub
- Public Function ConvertFileToBase64(ByVal fileName As String) As String
- Return Convert.ToBase64String(System.IO.File.ReadAllBytes(fileName))
- End Function
- Public Sub AddItem(ByVal s As String)
- If Not s Is Nothing Then
- If (s.Contains("/FileAccepted")) Then 'Ändern
- MsgBox("File successfully uploaded!", MsgBoxStyle.Information)
- End If
- If (s.Contains("/FileAlreadyExist")) Then 'Ändern
- MsgBox("This file does already exist!", MsgBoxStyle.Exclamation)
- ' MsgBox("test")
- End If
- If (s.Contains("/SendFileListToClient")) Then
- Dim str() = {s}
- For Each sx In str
- Dim regx = New Regex(" +")
- Dim splitString = regx.Split(s)
- Dim List As String = (splitString(1))
- Dim ListConvert As New List(Of String)()
- ListConvert.Clear()
- lvFiles.Items.Clear() 'Ändern
- List = List.Replace("[+1]", vbNewLine)
- List = List.Replace("[~1]", "")
- Dim Ar() As String = Split(List, Environment.NewLine)
- For Each Eintrag As String In Ar
- ListConvert.Add(Eintrag)
- Next
- For Each val As String In ListConvert
- If Not (String.IsNullOrEmpty(val)) Then
- Dim LW As New ListViewItem
- LW.Text = val.Substring(0, val.Length - 4)
- If (val.Substring(0, val.Length - 4).Substring(Math.Max(0, val.Substring(0, val.Length - 4).Length - 4)) = ".exe") Then
- LW.ImageIndex = 0
- ElseIf (val.Substring(0, val.Length - 4).Substring(Math.Max(0, val.Substring(0, val.Length - 4).Length - 5)) = ".html") Then
- LW.ImageIndex = 1
- ElseIf (val.Substring(0, val.Length - 4).Substring(Math.Max(0, val.Substring(0, val.Length - 4).Length - 4)) = ".php") Then
- LW.ImageIndex = 2
- ElseIf (val.Substring(0, val.Length - 4).Substring(Math.Max(0, val.Substring(0, val.Length - 4).Length - 4)) = ".txt") Then
- LW.ImageIndex = 3
- ElseIf (val.Substring(0, val.Length - 4).Substring(Math.Max(0, val.Substring(0, val.Length - 4).Length - 4)) = ".mp4") Then
- LW.ImageIndex = 4
- ElseIf (val.Substring(0, val.Length - 4).Substring(Math.Max(0, val.Substring(0, val.Length - 4).Length - 4)) = ".jpg") Then
- LW.ImageIndex = 6
- ElseIf (val.Substring(0, val.Length - 4).Substring(Math.Max(0, val.Substring(0, val.Length - 4).Length - 5)) = ".jpeg") Then
- LW.ImageIndex = 6
- ElseIf (val.Substring(0, val.Length - 4).Substring(Math.Max(0, val.Substring(0, val.Length - 4).Length - 4)) = ".png") Then
- LW.ImageIndex = 7
- Else
- LW.ImageIndex = 5
- End If
- lvFiles.Items.Add(LW) 'Ändern
- End If
- Next
- Next
- End If
- If (s.Contains("/SendFileToClient")) Then
- Dim str() = {s}
- For Each sx In str
- Dim regx = New Regex(" +")
- Dim splitString = regx.Split(s)
- Dim BaseFile As String = splitString(1)
- If Not My.Computer.FileSystem.FileExists(My.Computer.FileSystem.CurrentDirectory & "\Files\" & lvFiles.SelectedItems(0).SubItems(0).Text) Then 'Ändern
- Dim bytes() As Byte
- bytes = System.Convert.FromBase64String(BaseFile)
- 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
- writer.Write(bytes)
- writer.Close()
- MsgBox("File successfully downloaded!", MsgBoxStyle.Information)
- End If
- Next
- End If
- End If
- End Sub
- Public Function ConnectToServer() As Object
- Try
- client.Connect("127.0.0.1", 8000)
- If client.Connected Then
- stream = client.GetStream
- streamw = New StreamWriter(stream)
- streamr = New StreamReader(stream)
- ListenThread.Start()
- Else
- MsgBox("The server is not reachable!", MsgBoxStyle.Exclamation)
- Application.Exit()
- End If
- Catch ex As Exception
- MsgBox("The server is not reachable!", MsgBoxStyle.Exclamation)
- Application.Exit()
- End Try
- End Function
- Public Function SendPacket(ByVal Content As String) As Object
- streamw.WriteLine(Content)
- streamw.Flush()
- End Function
- Public Function RequestFileList() As Object
- SendPacket("/RequestFileList")
- End Function
- Public Function DownloadFile(ByVal Filename As String) As Object
- SendPacket("/RequestUpload " & Filename)
- End Function
- Public Function SendFile(ByVal Basefile As String, ByVal Filename As String) As Object
- SendPacket("/SendFile " & Basefile & " " & Filename)
- End Function
- Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnDownload.Click
- DownloadFile(lvFiles.SelectedItems.Item(0).SubItems(0).Text)
- End Sub
- Private Sub Button2_Click(sender As Object, e As EventArgs) Handles btnUpload.Click
- Dim ofd As New OpenFileDialog
- If (ofd.ShowDialog() = DialogResult.OK) Then
- Dim SelectedFileWithPath As String
- Dim FileName As String = System.IO.Path.GetFileName(ofd.FileName)
- Dim BaseFile As String = ""
- SelectedFileWithPath = ofd.FileName
- SelectedFileWithPath = SelectedFileWithPath.Replace(" ", "[+1]")
- BaseFile = ConvertFileToBase64(ofd.FileName)
- If (BaseFile.Length < 1398104) Then
- SendFile(BaseFile, FileName)
- Else
- MsgBox("This file is too large!", MsgBoxStyle.Exclamation)
- End If
- End If
- End Sub
- Private Sub Button3_Click(sender As Object, e As EventArgs) Handles btnAktualisieren.Click
- RequestFileList()
- End Sub
- Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
- ConnectToServer()
- End Sub
- 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
Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von „xored“ ()