使用Visual basic 6.0,我建立了一个到and服务器的Winsock HTTP连接,该服务器发送数据后立即关闭。(Connection: keep-alive,对此服务器没有任何好处)
下面是我的一段代码:
sck.SendData "GET /? HTTP/1.1" & vbNewLine & _
"Host: example.org" & vbNewLine & _
"Connection: keep-alive" & vbNewLine & vbNewLine
'// Wait for full Data:
Dim DATA As String
While (Not isEOF(DATA)) And sck.State = sckConnected
If sck.State = sckConnected Then sck.PeekData DATA
Sleep 10: DoEvents
Wend
If sck.State <> sckConnected Then
'// When this Fires, my data is missing the 25% of it's rest.
'// It is received corectly acording to Wireshark, but Winsock
'// closes the socket befor I can get the rest to the DATA variable.
MsgBox "This happends randomly 10% of the times.", vbInformation
End If
Clipboard.Clear
Clipboard.SetText DATA
Msgbox DATA
sck.CloseisEOF()函数执行一些检查,以查看数据是否完整和就绪(读取content-length、< /html>标记或空字符)。不需要在这里张贴,因为它很大,相信我,这不是问题。
当您对已关闭的套接字使用:sck.GetData或sck.PeekData时,会得到一个错误。那么,在套接字关闭之后,如何从套接字中获取数据呢?
这里的重点是,Winsock在我可以获得其余数据之前关闭套接字的情况有10%。我尝试了所有方法来解决这个问题(使用事件处理程序,使用GetData而不是PeekData,等等),但我连接到的web服务器仍然随机地收到相同的错误。
使用Winsock直接获取和等待数据的正确方式是什么?我在这段代码中做错了什么?
发布于 2012-11-28 15:33:47
你能试试下面的代码吗?
'1 form with :
' 1 winsock control : name=Winsock1
' 1 command button : name=Command1
Option Explicit
Private Sub Command1_Click()
With Winsock1
.Connect "<your server>", <your port>
Do
DoEvents
Loop Until .State = sckConnected
.SendData <your command>
End With 'Winsock1
End Sub
Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim strData As String
Winsock1.GetData strData
ProcessData strData
End Sub
Private Sub ProcessData(strData As String)
Static strTotal As String
strTotal = strTotal & strData
If IsComplete(strTotal) Then 'your check to see if data is complete
Winsock1.Close
End If
End Sub我只是运行了几次,在检索大块数据时从不遗漏任何数据(在数据完成之前涵盖了几个数据到达事件)
还要确保在ProcessData过程中的某个地方做其他事情,当然,在做完事情之后还要清空strTotal :)
发布于 2012-11-28 17:59:45
你的问题显示了几个误解。
发布于 2020-06-23 01:21:35
在一端关闭socket,然后从另一端调用recv并检查返回值。
https://stackoverflow.com/questions/13599274
复制相似问题