1
**Server Code**

Dim serverSocket As Socket
Dim clientSocket As Socket
Dim PubIP as String = "82.XX.XX.XX"
Dim LocalIP as String = "192.XX.XX.XX"

Dim byteData(1023) As Byte

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim host As String = Dns.GetHostName
    Dim ip As IPHostEntry = Dns.GetHostEntry(host)
    serverSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
    Dim IpEndPoint As IPEndPoint = New IPEndPoint(System.Net.IPAddress.Parse(PubIP), 8080) 
    Me.Text = IpEndPoint.ToString
    serverSocket.Bind(IpEndPoint) 'it can't bind public ip but i need public ip to run the client from other pc and connect to server for chating.
    serverSocket.Listen(5)
    serverSocket.BeginAccept(New AsyncCallback(AddressOf OnAccept), Nothing)
End Sub

**Client Code**

Dim clientSocket As Socket
Dim byteData(1023) As Byte

Dim PubIP as String = "82.XX.XX.XX"
Dim LocalIP as String = "192.XX.XX.XX"

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    clientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
    Dim ipAddress As IPAddress = ipAddress.Parse(PubIP)
    Dim ipEndPoint As IPEndPoint = New IPEndPoint(ipAddress, 8080)
    clientSocket.BeginConnect(ipEndPoint, New AsyncCallback(AddressOf OnConnect), Nothing)
End Sub

当我使用 localip 运行服务器时,它运行良好,我只能从我的计算机(服务器运行的地方)连接客户端。如果我尝试从另一台计算机运行客户端,它将无法连接到服务器。

所以我分配了公共 IP,但是当我运行程序时 Visual Studio 显示此错误:请求的地址在其上下文中无效。

所以我被困在这里。如果从我的电脑运行,我只能连接客户端,但我需要将客户端从我的朋友电脑连接到我电脑中的服务器。

欢迎任何替代方式。

4

1 回答 1

1

使用IPAddress.Any而不是特定的 IP 地址来使您的服务器接受所有接口上的连接。

除此之外,由于您提到“本地”和“公共”IP 地址,您需要了解网络地址转换端口转发

于 2013-01-18T19:24:59.757 回答