如何确保从服务器向客户端发送多个串行数据

时间:2019-04-22 08:18:21

标签: vb.net callback network-programming tcpclient tcplistener

我的程序分为两部分,服务器和客户端。当客户端连接到服务器时,此时,服务器应向客户端发送数字1到10。但只会发送一个或两个第一个号码。

这是变量:

Dim pClient As TcpClient
Dim Listener As TcpListener
Dim mre As New Threading.ManualResetEvent(False)

这是服务器端: 在AcceptClient子目录中,我创建了一个for循环,用于将数字1到10发送给客户端。

Sub Main()
    mre.Reset()
    Listener = New TcpListener(IPAddress.Any, 6000)
    Listener.Start()
    Listener.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listener)
    mre.WaitOne()
End Sub

Sub AcceptClient(ByVal ar As IAsyncResult)
    pClient = Listener.EndAcceptTcpClient(ar)
    Listener.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listener)
    For i = 1 To 10
        Send(i)
    Next
End Sub

Public Sub Send(ByVal Messsage As String)
    Dim sendMessage As StreamWriter = New StreamWriter(pClient.GetStream)
    sendMessage.WriteLine(Messsage)
    sendMessage.Flush()
End Sub

这是客户端:

Sub Main()
    mre.Reset()
    Try
        client = New TcpClient("localhost", 6000)
        client.GetStream.BeginRead(New Byte() {0}, 0, 0, New AsyncCallback(AddressOf read), client.GetStream)
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
    mre.WaitOne()
End Sub

Sub read(ByVal ar As IAsyncResult)
    Try
        Dim ns As NetworkStream = ar.AsyncState
        Dim l As Int16 = ns.EndRead(ar)
        Dim msg As String = New StreamReader(ns).ReadLine
        Console.WriteLine(msg)
        ns.BeginRead(New Byte() {0}, 0, 0, New AsyncCallback(AddressOf read), ns)
    Catch ex As Exception
        MsgBox(ex.Message)
        Exit Sub
    End Try
End Sub

我想知道如何更正此代码以发送所有这些号码?

0 个答案:

没有答案