我正在尝试创建一个简单的客户端/服务器应用程序。非常基本 - 客户端连接到服务器,客户端向服务器发送消息 - 服务器接收消息并广播到任何其他连接的客户端。
正如我所说 - 它应该是简单的,并且是为了自我教导更好的理解。
据我所知,客户端正在发送数据,我相信难以接收数据包的服务器。有人会介意让我知道我的代码是否有明显的错误。
非常感谢提前。
客户端
Imports System.Net ' for IPAddress
Imports System.Net.Sockets 'for TcpListener
Imports System.Text
Module testClient
''' <summary>
''' CLIENT
''' </summary>
''' <remarks></remarks>
Sub Main()
Dim aString As String
Dim port As Integer
Dim localAddr As IPAddress
Dim client As TcpClient
Dim stream As NetworkStream
Dim tempSocket
Try
port = 2302
localAddr = IPAddress.Loopback
Do
Console.Write("are you ready to connect to your server? (y/n) ")
aString = Console.ReadLine()
Loop Until aString = "y" Or aString = "n"
Do
If aString = "y" Then
'Create a TcpClient.
client = New TcpClient(localAddr.ToString, port)
Console.Write(" Connencted to : " & IPAddress.Parse(CType(client.Client.LocalEndPoint, IPEndPoint).Address.ToString).ToString & " ")
End If
Console.Write("Ready to quit? (y/n)")
aString = Console.ReadLine()
If aString <> "y" Or aString <> "n" Then
'this is where we send a message to the server
Dim endPoint As New IPEndPoint(localAddr, port)
tempSocket = New Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
tempSocket.Connect(endPoint)
stream = New NetworkStream(tempSocket)
Dim outStream As Byte() = Text.Encoding.ASCII.GetBytes(aString)
stream.Write(outStream, 0, outStream.Count)
stream.Flush()
End If
Loop Until aString = "y"
Catch ex As Exception
Console.Write(ex.ToString)
End Try
End Sub
End Module
服务器:
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Module testServer
Dim port As Integer
Dim localAddr As IPAddress
Dim server As TcpListener
Dim client As TcpClient
Dim bytesFrom As Byte()
''' <summary>
''' Server
''' </summary>
''' <remarks></remarks>
Dim tempSocket
Sub Main()
Try
port = 2302
localAddr = IPAddress.Loopback
server = New TcpListener(localAddr, port)
server.Start()
Console.WriteLine("Server ready")
client = server.AcceptTcpClient
Console.WriteLine("Connected to " & IPAddress.Parse(CType(client.Client.LocalEndPoint, IPEndPoint).Address.ToString).ToString)
getmessage()
Catch ex As Exception
Console.WriteLine(ex.ToString)
End Try
End Sub
Sub getmessage()
Dim endPoint As New IPEndPoint(localAddr, port)
Dim clientSocket As New TcpClient
Try
clientSocket.Connect(endPoint)
Dim Stream As NetworkStream = clientSocket.GetStream()
Stream.Read(bytesFrom, 0, bytesFrom.Count)
Dim dataFromClient As String = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
printOut(dataFromClient)
Catch ex As Exception
Console.WriteLine(ex.ToString)
Finally
clientSocket.Close()
End Try
End Sub
Sub printOut(msg As String)
Console.WriteLine(msg)
End Sub
End Module