2

I am looking for help with writing a server application to serve an updating text stream to clients. My requirements are as follows:

I need to be able to have a client request information on server port 7878 and receive back an initial set of values, the changed values would then be reported every 5 seconds. The hanging point for me has been connecting another client. I need to be able to connect a 2nd (or 3rd or 4th) client while the first is still running. The second client would receive the initial values and then begin updating as well. I need the two streams to be completely independent of each other. Is this possible with VB.Net and TCP sockets?

Edit to add: I have pasted some of my code below of what I can share. WriteLog is a separate sub that isn't really relevant to my problem. This code will allow for a client to connect and then allow for another client to connect, but all transmissions to the 1st client stop on a new connection.

    Public Class ServerApp

    Dim serverSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
    Dim clientSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

Private Sub ServerApp_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    WriteLog(String.Format("Start of form load.."))

    Dim listener As New Thread(New ThreadStart(AddressOf ListenForRequests))
    listener.IsBackground = True
    listener.Start()
End Sub

Private Sub ListenForRequests()

    Dim CONNECT_QUEUE_LENGTH As Integer = 4

    serverSocket.Bind(New IPEndPoint(IPAddress.Any, 7878))
    serverSocket.Listen(CONNECT_QUEUE_LENGTH)
    serverSocket.BeginAccept(New AsyncCallback(AddressOf OnAccept), Nothing)
End Sub

Private Sub OnAccept(ByVal ar As IAsyncResult)
    clientSocket = serverSocket.EndAccept(ar)
    serverSocket.BeginAccept(New AsyncCallback(AddressOf OnAccept), Nothing)
    WriteLog("just accepted new client")

    Try
        clientSocket.Send(Encoding.UTF8.GetBytes("first response on connect"), SocketFlags.None)
        While True
            clientSocket.Send(Encoding.UTF8.GetBytes("string of updates"), SocketFlags.None)
            Thread.Sleep(5000)
        End While
    Catch ex As Exception
        WriteLog(ex.Message)
        WriteLog("Remote host has disconnected")
    End Try

End Sub

End Class
user2207822
  • 33
  • 1
  • 6
  • Are you setting up a local server? – Sam May 21 '13 at 14:59
  • @Sam I am only developing the local server application (currently a Windows Form). I have no control over the client application. It is 3rd party supplied (and operates on TCP) and is supposed to when activated make periodic requests on port 7878 of the machine hosting the local server. Does that help? – user2207822 May 21 '13 at 15:29
  • Yes, that helped. So what have you written so far? – Sam May 21 '13 at 15:34
  • @Sam I have added some code to the original post to give you an idea of where I am at. I am also working through some of the information you had previously given me. The first link I had already seen and I'm not sure that I can use UDP since I can't touch the client code. Thank you for your help! – user2207822 May 21 '13 at 16:13
  • @Sam also it may be helpful to know that I am dealing with small numbers of clients. I can't imagine a scenario where I would see more than 3-4 simultaneous clients. – user2207822 May 21 '13 at 16:26
  • Thanks, i'll get back to you when i find something... – Sam May 21 '13 at 16:28
  • [This](http://vb.net-informations.com/communications/vb.net_multithreaded_server_socket_programming.htm), and [this](http://www.leadwerks.com/werkspace/topic/6514-a-simple-tcp-server-for-multiple-connections/) might help. – Sam May 21 '13 at 17:03
  • @Sam I think the code on the last link you sent is going to be able to help. I have dug into it some. I know I can send the same message out to all clients with it, but I think I can modify it to work for my purposes too. I would like to give you credit for the answer. If you will post the link as answer I can mark this closed once I implement it. Thanks again. – user2207822 May 21 '13 at 18:41
  • Sure, i'm just sorry that i couldn't help much beside digging for links, (i hardly ever work TCP, only UDP). If you have anymore questions i'll be glad to help. – Sam May 21 '13 at 18:53

1 Answers1

0

I recommend trying out the UdpClient class, i find it easier to use and understand.

Now for some code...

Imports System.Net.Sockets
Imports System.Threading
Imports System.Text
Imports System.Net

Public Class Form1

    Private port As Integer = 7878
    Private Const broadcastAddress As String = "255.255.255.255"
    Private receivingClient As UdpClient
    Private sendingClient As UdpClient
    Private myTextStream As String = "Blah blah blah"
    Private busy As Boolean = False

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        InitializeSender()
        InitializeReceiver()
    End Sub

    Private Sub InitializeSender()
        Try
            sendingClient = New UdpClient(broadcastAddress, port)
            sendingClient.EnableBroadcast = True
        Catch ex As Exception
            MsgBox("Error, unable to setup sender client on port " & port & "." & vbNewLine & vbNewLine & ex.ToString)
        End Try
    End Sub

    Private Sub InitializeReceiver()
        Try
            receivingClient = New UdpClient(port)
            ThreadPool.QueueUserWorkItem(AddressOf Receiver)
        Catch ex As Exception
            MsgBox("Error, unable to setup receiver on port " & port & "." & vbNewLine & vbNewLine & ex.ToString)
            End
        End Try
    End Sub

    Private Sub sendStream()
        busy = True
        Dim i% = 0
        Do While i < 4
            If myTextStream <> "" Then
                Dim data() As Byte = Encoding.ASCII.GetBytes(myTextStream)
                Try
                    sendingClient.Send(data, data.Length)
                Catch ex As Exception
                    MsgBox("Error, unable to send stream." & vbNewLine & vbNewLine & ex.ToString)
                    End
                End Try
            End If
            Thread.Sleep(5000)
            i += 1
        Loop
        busy = False
    End Sub

    Private Sub Receiver()
        Dim endPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, port)
        While True
            Dim data() As Byte
            data = receivingClient.Receive(endPoint)
            Dim incomingMessage As String = Encoding.ASCII.GetString(data)
            If incomingMessage = "what ever the client is requesting, for example," & "GET_VALUES" Then
                If busy = False Then Call sendStream()
            End If
        End While
    End Sub
End Class

A few links that may help: Here, here, here and here.

Community
  • 1
  • 1
Sam
  • 7,252
  • 16
  • 46
  • 65