我正在使用VB6,我想创建一个可以在 LAN 上运行的聊天应用程序。我使用了WinSock控件,但是当我运行该Listen()
函数时,我的套接字只侦听 127.0.0.1 而不是我计算机在 LAN 上的 IP。
为什么?有什么办法可以在局域网上监听我的 IP 吗?
通常,您会调用该Bind
方法来设置本地端口,并可选择指定要使用的适配器的本地 IP 地址。它应该默认为您系统的主适配器。然后你Listen
在没有参数的情况下调用。
您可以跳过然后Bind
设置,但除非在简单的单连接服务器场景中,否则不建议这样做。LocalPort
Listen
但是,这些都不能解释为什么默认选择您的环回地址。听起来像是盒子上的某种网络配置问题。
您需要设置 localport 属性(并且客户端需要连接到该端口)
'1 form with :
' 1 textbox : name=Text1
' 1 winsock control : name=Winsock1
Option Explicit
Private Sub Form_Load()
Text1.Move 0, 0, ScaleWidth, ScaleHeight 'position the textbox
With Winsock1
.LocalPort = 5001 'set the port to listen on
.Listen 'start listening
End With 'Winsock1
End Sub
Private Sub Winsock1_ConnectionRequest(ByVal requestID As Long)
With Winsock1
If .State <> sckClosed Then .Close 'close the port when not closed (you could also use another winsock control to accept the connection)
.Accept requestID 'accept the connection request
End With 'Winsock1
End Sub
Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim strData As String
Winsock1.GetData strData 'get the data
ProcessData strData 'process the data
End Sub
Private Sub Winsock1_Error(ByVal Number As Integer, Description As String, ByVal Scode As Long, ByVal Source As String, ByVal HelpFile As String, ByVal HelpContext As Long, CancelDisplay As Boolean)
MsgBox Description, vbCritical, "Error " & CStr(Number)
End Sub
Private Sub ProcessData(strData As String)
Text1.SelText = strData 'show the data
End Sub
相信你可以RemoteHost
在监听的时候设置控件上的属性来确定服务器会监听哪个网络地址。要侦听所有网络接口,您可以使用:
WinSock1.RemoteHost = "0.0.0.0"
WinSock1.Lsten()