嘿,我在 vb.net 中创建了一个基于局域网的应用程序,我已经创建了一个服务器和一个客户端,并为这两个程序员制作了一个发布版本。
服务器代码
Imports System.Net
Imports System.Net.Sockets
Module Module1
Dim isActive As Boolean
Sub Main()
Dim port As Integer 'this is port number
Dim localAddr As IPAddress 'Ip Address
Dim server As TcpListener ' for use tcp/ip protocol
Dim client As TcpClient
Dim aString As String
Dim negotiateStream As Security.NegotiateStream = Nothing
Dim d As DictionaryEntry
Try
port = 8888
localAddr = IPAddress.Loopback 'return the ipaddress of self
'creating the server
server = New TcpListener(localAddr, port)
server.Start()
Console.WriteLine("Server ready")
'this is a block method, it will wait for new connection
'before continuing
client = server.AcceptTcpClient
Console.WriteLine("Connected to " & IPAddress.Parse(CType(client.Client.LocalEndPoint, IPEndPoint).Address.ToString).ToString)
Console.WriteLine("Connected to " & client.ToString)
Do
Console.Write(" Ready to quit? (y/n)")
aString = Console.ReadLine()
If aString <> "y" Then
'do something
End If
Loop Until aString = "y" ' Or aString = "n"
Catch e As System.Exception
Console.WriteLine("Can't create the server : " + e.Message)
End Try
End Sub
End Module
客户端代码
Imports System.Net ' for IPAddress
Imports System.Net.Sockets 'for TcpListener
Imports System.Text
Public Class Form1
Dim aString As String
Dim port As Integer 'this is the port number
Dim localAddr As IPAddress ' this is the IP address
Dim client As TcpClient ' This is for the TCP/IP Protocol
Dim networkStream As NetworkStream 'use to send/recieve data
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ConnectToServer(localAddr, port)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
TextBox1.Text = "Press button to connect with the server"
port = 8888
localAddr = IPAddress.Loopback
Button2.Enabled = False
End Sub
Private Sub ConnectToServer(ByRef ipaddr, ByRef port)
Try
client = New TcpClient(localAddr.ToString, port)
TextBox1.Text = "Connencted to : " & IPAddress.Parse(CType(client.Client.LocalEndPoint, IPEndPoint).Address.ToString).ToString & " "
networkStream = client.GetStream()
Button1.Enabled = False
Button2.Enabled = True
Catch e As Exception
MsgBox(e.Message)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim outStream As Byte() = System.Text.Encoding.ASCII.GetBytes("Message from Client$")
networkStream.Write(outStream, 0, outStream.Length)
networkStream.Flush()
End Sub
End Class
现在,当我启动服务器并将client1连接到服务器时,会在服务器控制台上打印一条消息,例如“连接到客户端_ ”但现在它打开另一个客户端(client2)然后将其连接到服务器没有显示新消息为客户 2。