2012-12-12 210 views
2

我試圖ping消息到服務器,並得到一個消息與服務器上的總球員的數字值。不幸的是,下面的代碼會凍結,除非我刪除下面的一段代碼。VB.NET套接字發送和接收

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 

的平經過,但沒有返回值。有人能指出我做錯了什麼嗎?

+0

爲什麼'[Byte]'和'[String]'?他們工作正常,沒有括號... – Ryan

+0

如果你的數據恰好是256字節的倍數,那麼它會阻塞並永遠不會返回。代替嘗試使用'Loop While s.Available> 0'。 – Ryan

+0

結果仍然相同 – Moulijin

回答

1

你的循環讓它崩潰,我有類似的問題。你要做的是讓你的服務器多線程。你在這裏做的是無限循環遍歷代碼,這會導致當前線程凍結。如果你添加另一個線程,它將起作用。 Google(mutlithreaded socket programming)