vb.net 服务器 - 多个客户端不断处理不同的信息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16672671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:40:19  来源:igfitidea点击:

vb.net server - multiple clients continually processing different information

vb.netsocketsasynchronoustcptcplistener

提问by user2207822

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?

我需要能够在服务器端口 7878 上获得客户端请求信息并接收一组初始值,然后每 5 秒报告一次更改的值。我的悬念一直是连接另一个客户。我需要能够在第一个客户端仍在运行时连接第二个(或第三个或第四个)客户端。第二个客户端将接收初始值,然后也开始更新。我需要两个流完全相互独立。这可以用 VB.Net 和 TCP 套接字实现吗?

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.

编辑添加:我在下面粘贴了一些我可以分享的代码。WriteLog 是一个单独的子程序,与我的问题并不真正相关。此代码将允许客户端连接,然后允许另一个客户端连接,但所有到第一个客户端的传输都将在新连接上停止。

    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

采纳答案by Sam

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

我建议尝试使用UdpClient类,我发现它更易于使用和理解。

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, hereand here.

一些可能有帮助的链接:这里这里这里这里