vb.net中Winsock控件的使用(转载)
vb.net中Winsock控件的使用
以前我们在VB6.0中使用Winsock控件用于网络信息交流,现在转入VB.net 常使用Socket来传送信息.如果我们继续使用Winsock就需要注意许多方面,比如:VB6的Accept RequestID在VB.net中变为了 Accept(e.requestID)……下面详细说明各项属性.
VB.net=================
Visual Basic 6.0WinSock Control控件与Visual Basic.NET的控件不同,
当Visual Basic 6.0WinSock Control控件在Visual Basic.NET中注册后,会转换并建立以下参考:
·AxMSWinsockLib
·MSWinsockLib
·经转换后,在VB.net中这样使用:
Friend WithEvents AxWinsock1 As AxMSWinsockLib.AxWinsock Friend WithEvents AxWinsock1 As AxMSWinsockLib.AxWinsock
... ...
Me.AxWinsock1 = New AxMSWinsockLib.AxWinsock() Me.AxWinsock1 = New AxMSWinsockLib.AxWinsock()
CType(Me.AxWinsock1, _ CType(Me.AxWinsock1, _
System.ComponentModel.ISupportInitialize).BeginInit() System.ComponentModel.ISupportInitialize).BeginInit()
... ...
Me.AxWinsock1.Name = "AxWinsock1" Me.AxWinsock1.Name = "AxWinsock1"
Me.AxWinsock1.OcxState = _ Me.AxWinsock1.OcxState = _
CType(resources.GetObject("AxWinsock1.OcxState"), _ CType(resources.GetObject("AxWinsock1.OcxState"), _
System.Windows.Forms.AxHost.State) System.Windows.Forms.AxHost.State)
... ...
CType(Me.AxWinsock1, _ CType(Me.AxWinsock1, _
System.ComponentModel.ISupportInitialize).EndInit() System.ComponentModel.ISupportInitialize).EndInit()
下面有一个实例:
’{}{}{{}{}{{{}{{}{{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{
'在Server端,使用TCP协议:
WskServer.Protocol = MSWinsockLib.ProtocolConstants.sckTCPProtocol
WskServer.LocalPort = 555
'按下Listen按钮,Server端用Listen方法,开始监听端口。
WskServer.Listen()
'Client端连接…………
Private Sub WskServer_ConnectionRequest(ByVal sender As Object, ByVal e As AxMSWinsockLib.DMSWinsockControlEvents_ConnectionRequestEvent) Handles WskServer.ConnectionRequest
WskServer.Accept(e.requestID)
WskServer.SendData("CLOSE")
End Sub
======================================================================
'在Client端,也使用TCP协议:
WskClient。RemotePort = 555
WskClient.Connect()
Private Sub WskClient_DataArrival(ByVal sender As Object, ByVal e As AxMSWinsockLib.DMSWinsockControlEvents_DataArrivalEvent) Handles WskClient.DataArrival
If WskClient.CtlState <> MSWinsockLib.StateConstants.sckClosed Then‘注意Winsock的即使状态用CtlState判断!如果使用以前的State属性,就会这样:“State”是“AxMSWinsockLib.AxWinsock”中的类型,不能用作表达式。 ”
WskClient.Close()
End If
End Sub
’===========================================================
WinSock的CtlState属性值:
错误发生 9 MSWinsockLib.StateConstants.sckError
连线正在关闭中 8 MSWinsockLib.StateConstants.sckClosing
已与服务端完成连接 7 MSWinsockLib.StateConstants.sckConnected
正在与服务器连接中 6 MSWinsockLib.StateConstants.sckConnecting
已经找到服务端IP 5 MSWinsockLib.StateConstants.sckHostResolved
正在找寻服务器IP 4 MSWinsockLib.StateConstants.sckResolvingHost
正在连线中 3 MSWinsockLib.StateConstants.sckConnectionPending
正在等候连线中 2 MSWinsockLib.StateConstants.sckListening
已开启 1 MSWinsockLib.StateConstants.sckOpen
已关闭(默认值)0 MSWinsockLib.StateConstants.sckClosed