VB.NET套接字发送和接收

时间:2012-12-12 04:13:57

标签: vb.net

我正在尝试将消息ping到服务器并使用服务器上的总播放器的数值来获取消息。不幸的是,除非我删除下面的代码,否则下面的代码会冻结。

Public Shared Function SocketSendReceive(server As String, port As Integer) As String
    'Set up variables and String to write to the server. 
    Dim ascii As Encoding = Encoding.ASCII
    Dim request As String = (DoubleChar(Len(Chr(35))) + Chr(CheckSum(Chr(35)) * 20 Mod 194) + Chr(0) + Chr(35))
    Dim bytesSent As [Byte]() = ascii.GetBytes(request)
    Dim bytesReceived(255) As [Byte]

    ' Create a socket connection with the specified server and port. 
    Dim s As Socket = ConnectSocket(server, port)

    If s Is Nothing Then
        Return "0"
    End If
    ' Send request to the server.
    s.Send(bytesSent, bytesSent.Length, 0)

    ' Receive the server  home page content. 
    Dim bytes As Int32

    ' Read the first 256 bytes. 
    Dim page As [String] = "0"

    ' The following will block until the page is transmitted. 
    Do
        bytes = s.Receive(bytesReceived, bytesReceived.Length, 0)
        page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes)
    Loop While bytes > 0
    Return page
End Function

当我删除这部分代码时:

    Do
        bytes = s.Receive(bytesReceived, bytesReceived.Length, 0)
        page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes)
    Loop While bytes > 0

ping通过但不返回值。有人能指出我做错了吗?

1 个答案:

答案 0 :(得分:1)

你的循环让它崩溃了,我遇到了类似的问题。你要做的是让你的服务器多线程。你在这里做的是循环遍历代码无限次,这使得当前线程冻结。如果你添加另一个线程,它将工作。谷歌(mutlithreaded socket编程)