wangl0907
wangl0907
2016-04-06 07:10

vb编程 我使用的TCPListener和异步方法BeginAcceptTCPClient多个客户端 连接TCP服务器

  • 异步
  • 编程

Public Sub TCPlisten()

try

    Dim listener As New TcpListener(IPAddress.Any, Local_Port) 
    listener.Start()
    listener.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), listener) '异步操作

Public Sub AcceptClient(result As IAsyncResult)
try
Dim tempListener As TcpListener = CType(result.AsyncState, TcpListener)

    Dim client As TcpClient = tempListener.EndAcceptTcpClient(result)
    Dim bytes(1024) As Byte
    Dim data As String = Nothing
    Dim stream As NetworkStream = client.GetStream()
    Dim i As Int32

    i = stream.Read(bytes, 0, bytes.Length)
    listener.BeginAcceptTcpClient(AddressOf AcceptClient, listener)  //应该加在while循环前面吧
    While True     //这里的循环怎么写可以替换成异步通信
            data = System.Text.Encoding.ASCII.GetString(bytes, 0, i) '数字0表示从缓冲区的起始位置,
            receiveBytes = System.Text.Encoding.ASCII.GetBytes(data) '转换为字节数
            Me.BeginInvoke(New System.EventHandler(AddressOf TCP_Refresh), receiveBytes) //异步委托

            i = stream.Read(bytes, 0, bytes.Length)

    End While

            //这里有部分内容不懂,怎么处理网络流关闭???
    Catch ex As Exception
        listener.Stop()
        listener = Nothing
    End Try

End Sub

Public Sub TCPserver(sender As Object, e As EventArgs)
    Try
        Dim str As String = Nothing
        str = System.Text.Encoding.ASCII.GetString(sender)
        TextBox1.Text = str & vbCrLf & TextBox1.Text
    Catch ex As Exception
        MsgBox(e.ToString())
    End Try
    //这里的网络流关闭写在哪里啊??? 大家帮帮忙吧???
   ‘ stream.Close()

End Sub


现在问题是,只要客户端发送数据,服务器客户端可以接收数据,就是发送中间会出现没有反应???
发现断开连接时候会出现服务器端不会响应,怎么办???


特别是其中的异步TCP编程
看了这篇文章有了很大的认识
http://blog.csdn.net/jjjfox/article/details/8212271
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

10条回答