我正在使用 vb.net 中的套接字编程技术制作一个简单的聊天系统。它在本地网络上运行良好,但如何通过互联网使用它..我也尝试在我的路由器上进行端口转发......可能是我的方式是错误的。请告诉我端口转发的正确方法..并告诉我如何将客户端连接到服务器???我必须使用服务器系统的公共 IP 吗???
服务器端代码是这样的:
Imports System.Net.Sockets
Module Module1
Sub Main()
Console.WriteLine("")
Dim clientListener As New TcpListener(12380)
clientListener.Stop()
clientListener.Start()
Console.WriteLine("")
Dim mySocket As Socket = clientListener.AcceptSocket()
Console.WriteLine("")
Dim recieveBuff(225) As Byte
mySocket.Receive(recieveBuff, recieveBuff.Length, SocketFlags.None)
Dim str As String = System.Text.Encoding.ASCII.GetString(recieveBuff, 0, recieveBuff.Length).Trim(Microsoft.VisualBasic.ChrW(0))
While Not str.StartsWith(".")
Console.WriteLine(str)
mySocket.Receive(recieveBuff, recieveBuff.Length, SocketFlags.None)
str = System.Text.Encoding.ASCII.GetString(recieveBuff, 0, recieveBuff.Length).Trim(Microsoft.VisualBasic.ChrW(0))
End While
Console.WriteLine("")
clientListener.Stop()
End Sub
End Module
客户端代码是这样的:(这两个都是控制台应用程序)
Imports System.Net.Sockets
Imports System.IO
Module Module1
Sub Main()
Try
Console.WriteLine("Connecting to localhost ")
Dim serverListener As New TcpClient("192.168.1.103", 12380)
Dim readStream As Stream = serverListener.GetStream
serverListener.SendBufferSize = 256
Console.WriteLine("Input Lines:")
Dim str As String = Console.ReadLine()
While 370
Dim sendBuff As Byte() = System.Text.Encoding.ASCII.GetBytes(str)
readStream.Write(sendBuff, 0, sendBuff.Length)
If str.StartsWith(".") Then
GoTo Done
End If
str = Console.ReadLine()
End While
Done: Console.WriteLine("Done")
Catch exp As Exception
Console.WriteLine("Exception: " + exp.ToString())
End Try
End Sub
End Module