Chat program that sends file from directory

samiam41
samiam41 used Ask the Experts™
on
I have a VB.NET 2015 program that has a Tcp socket Listener and client applications to send messages to workers by their ip address.
I need to be able to pick up a file from a directory and send the text files data to a client machine connected to the listener. The file name is the ip address. When the file gets put into the directory is when the listener will pickup the file and send it to the appropriate ip address. I can pickup the file but the message gets sent to all clients connected to the listener.  My code is below.

Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Drawing.Size
Imports System.Net.IPAddress
Imports Microsoft.VisualBasic.FileSystem
Imports System.Windows.Forms
Imports System.ComponentModel




Public Class Form1
    Public watchfolder As FileSystemWatcher
    Dim ServerStatus As Boolean = False
    Dim ServerTrying = False
    Dim Server As TcpListener
    Dim Clients As New List(Of TcpClient)

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        CheckForIllegalCrossThreadCalls = False

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        StartServer()
        'Dim CN_GetData2015 As New CN_GetData2015
        'CN_GetData2015.Show()
        Button3.PerformClick()

    End Sub

    Function StartServer()
        If ServerStatus = False Then
            ServerTrying = True
            Try
                Server = New TcpListener(IPAddress.Any, 4305)
                Server.Start()
                ServerStatus = True
                Threading.ThreadPool.QueueUserWorkItem(AddressOf Handler_Client)
            Catch ex As Exception
                ServerStatus = False
            End Try
            ServerTrying = False
        End If
        Return True
    End Function

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        StopServer()
    End Sub
    Function StopServer()

        If ServerStatus = True Then
            ServerTrying = True
            Try
                For Each Client As TcpClient In Clients
                    Client.Close()
                Next
                Server.Stop()
                ServerStatus = False
            Catch ex As Exception
                StopServer()

            End Try
        End If
        Return True
    End Function

    Function Handler_Client(ByVal state As Object)
        Dim TempClient As TcpClient
        Try
            Using Client As TcpClient = Server.AcceptTcpClient
                If ServerTrying = False Then
                    Threading.ThreadPool.QueueUserWorkItem(AddressOf Handler_Client)
                End If
                Dim requesterIP As String = Client.Client.RemoteEndPoint.ToString().Split(New Char() {":"})(0)
                Clients.Add(Client)
                TempClient = Client
                Dim TX As New StreamWriter(Client.GetStream)
                Dim RX As New StreamReader(Client.GetStream)
                If RX.BaseStream.CanRead = True Then
                    While RX.BaseStream.CanRead = True
                        Dim RawData As String = RX.ReadLine
                        RichTextBox1.Text += requesterIP + ">>" + RawData + vbNewLine
                    End While
                End If
                If RX.BaseStream.CanRead = False Then
                    Client.Close()
                    Clients.Remove(Client)
                End If

            End Using
            If TempClient.GetStream.CanRead = False Then
                TempClient.Close()
                Clients.Remove(TempClient)
            End If
        Catch ex As Exception
            'Client.Client.RemoteEndPoint.ToString
        End Try
    End Function

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        watchfolder = New System.IO.FileSystemWatcher()

        'this is the path we want to monitor
        watchfolder.Path = "file path"
        watchfolder.NotifyFilter = IO.NotifyFilters.DirectoryName
            watchfolder.NotifyFilter = watchfolder.NotifyFilter Or
                                       IO.NotifyFilters.FileName
            watchfolder.NotifyFilter = watchfolder.NotifyFilter Or
                               IO.NotifyFilters.Attributes

            ' add the handler to each event

            AddHandler watchfolder.Created, (AddressOf logchange)

            'Set this property to true to start watching
            watchfolder.EnableRaisingEvents = True

        Threading.ThreadPool.QueueUserWorkItem(AddressOf SendToClients, TextBox1.Text)
        TextBox1.Text = ""


    End Sub
    Function SendToClients(ByVal Data As String)
        If ServerStatus = True Then
            If Clients.Count > 0 Then

                Try
                    For Each Client As TcpClient In Clients
                        Dim TX1 As New StreamWriter(Client.GetStream)
                        ''Dim RX1 As New StreamReader(Client.GetStream)
                        TX1.WriteLine(Data)
                        TX1.Flush()
                    Next
                Catch ex As Exception

                End Try
            End If
        End If
        Return True
    End Function
    Private Sub logchange(ByVal source As Object, ByVal e As System.IO.FileSystemEventArgs)
        Dim MessReader As String = ""
       
             Try

            If e.ChangeType = IO.WatcherChangeTypes.Created Then
                 System.Threading.Thread.Sleep(1000)
                
                MessReader = My.Computer.FileSystem.ReadAllText(e.FullPath)
               
                TextBox1.Text = MessReader

                      
            End If
            My.Computer.FileSystem.DeleteFile(e.FullPath)
            watchfolder.EnableRaisingEvents = False
            watchfolder.Dispose()
            Button3.PerformClick()

           
        Finally
        End Try
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        Console.WriteLine("MSG '" & TextBox1.Text & "'")
    End Sub
End Class

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
b

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial