.net vb socket 官网示例
来源:互联网 发布:数控系统编程指令格式 编辑:程序博客网 时间:2024/05/12 06:11
ImportsSystem ImportsSystem.Text
ImportsSystem.IO
ImportsSystem.Net
ImportsSystem.Net.Sockets
ImportsMicrosoft.VisualBasic
PublicClassGetSocket
PrivateSharedFunctionConnectSocket(server AsString, port AsInteger) AsSocket
Dim sAsSocket = Nothing
DimhostEntry AsIPHostEntry = Nothing
' Get host related information.
hostEntry = Dns.GetHostEntry(server)
' Loop through the AddressList to obtain the supportedAddressFamily. This is to avoid
' an exception that occurs when the host host IP Address is notcompatible with the address family
' (typical in the IPv6 case).
Dimaddress AsIPAddress
ForEachaddress In hostEntry.AddressList
DimendPoint AsNewIPEndPoint(address, port)
DimtempSocket AsNewSocket(endPoint.AddressFamily, SocketType.Stream,ProtocolType.Tcp)
tempSocket.Connect(endPoint)
If tempSocket.Connected Then
s = tempSocket
ExitFor
EndIf
Nextaddress
Return s
EndFunction
' This method requests thehome page content for the specified server.
PrivateSharedFunctionSocketSendReceive(server AsString, port AsInteger) AsString
'Set up variables and String to write to the server.
Dimascii AsEncoding = Encoding.ASCII
Dimrequest AsString = "GET /HTTP/1.1" + ControlChars.Cr + ControlChars.Lf + "Host: " + server +ControlChars.Cr + ControlChars.Lf + "Connection: Close" +ControlChars.Cr + ControlChars.Lf + ControlChars.Cr +ControlChars.Lf
DimbytesSent As[Byte]() = ascii.GetBytes(request)
DimbytesReceived(255) As[Byte]
' Create a socket connection with the specified server andport.
Dim sAsSocket = ConnectSocket(server, port)
If s IsNothingThen
Return "Connectionfailed"
EndIf
' Send request to the server.
s.Send(bytesSent, bytesSent.Length, 0)
' Receive the server home pagecontent.
Dimbytes AsInt32
' Read the first 256 bytes.
Dimpage as [String] = "Default HTMLpage on " + server + ":" + ControlChars.Cr +ControlChars.Lf
' The following will block until the page istransmitted.
Do
bytes = s.Receive(bytesReceived, bytesReceived.Length, 0)
page = page + Encoding.ASCII.GetString(bytesReceived, 0,bytes)
LoopWhilebytes > 0
Return page
EndFunction
'Entry point which delegatesto C-style main Private Function
PublicOverloadsSharedSubMain()
Main(System.Environment.GetCommandLineArgs())
EndSub
OverloadsPrivateSharedSubMain(args() AsString)
Dimhost AsString
ImportsSystem.IO
ImportsSystem.Net
ImportsSystem.Net.Sockets
ImportsMicrosoft.VisualBasic
PublicClassGetSocket