我正在寻求有关编写服务器应用程序以向客户端提供更新文本流的帮助。我的要求如下:
我需要能够在服务器端口 7878 上获得客户端请求信息并接收一组初始值,然后每 5 秒报告一次更改的值。对我来说,关键是连接另一个客户端。我需要能够在第一个客户端仍在运行时连接第二个(或第三个或第四个)客户端。第二个客户端将接收初始值,然后也开始更新。我需要两个流完全相互独立。VB.Net 和 TCP 套接字可以做到这一点吗?
编辑添加:我在下面粘贴了一些我可以分享的代码。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