**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显示了这个错误:请求的地址在其上下文中无效。
所以我被困在这里。我只能连接客户端,如果从我的电脑运行,但我需要将客户端从我的朋友电脑连接到我的电脑上的服务器。
欢迎任何其他方式。
答案 0 :(得分:1)
使用IPAddress.Any
而不是特定的IP地址,使您的服务器接受所有接口上的连接。
除此之外,由于您提及“本地”和“公开”IP地址,因此您需要了解Network Address Translation和port forwarding。