gpt4 book ai didi

windows - VB.net 服务编程和使用 TCP 套接字

转载 作者:可可西里 更新时间:2023-11-01 02:52:46 27 4
gpt4 key购买 nike

我遇到了一个问题,我很好奇是否有人可以帮助我解决它。我学习了 VB.NET 的客户端-服务器套接字编程教程。然后我尝试使用服务而不是程序来实现它。我了解它作为一个程序是如何工作的,但是当我尝试将它移植到一个服务时,它不起作用。当我运行该服务时,它会立即启动和停止。它永远不会建立联系。不幸的是,我不是 VB.net 程序员的好手,但到目前为止,我非常喜欢它来快速开发程序。

这项服务的理念是:

  1. 在计算机启动时运行
  2. 获取电脑的名称
  3. 将PC的名称发送给服务器

    一个。服务器然后获取名称并在数据库中查找

    返回客户端机器应该备份的时间

  4. 然后客户端计算机计算当前时间和它应该备份的时间并将所有内容放入毫秒。

  5. 然后机器通过运行 dos 命令启动程序在指定的时间备份。

现在回答一个我在论坛中发现的常见问题。为什么我不使用任务计划程序。好吧,我确实使用了任务计划,并让服务器以这种方式控制机器的时间。但是,有些计算机会进入休眠状态,我会说这种休眠状态影响了 20% 的机器。不,这种休眠状态不是 sleep 模式,也不是休眠状态。电脑开着,它们对鼠标移动的 react 非常快。我创建了一个将时间写入 C:\上的文件的服务,这一直有效。所以现在我决定在客户端机器上提供服务并让它与服务器通信。

关于创建服务和网络套接字编程,我收集的信息很少。不幸的是,我还没有发现任何将两者联系在一起的东西。我找到了一个 vb.net 客户端-服务器程序,它可以执行我想要的操作,但我希望它是一种服务而不是程序。我找到了一个使用服务器上的 PSEXEC 创建文件的临时解决方案,但这个过程实在是太简单了。

我做了退而求其次的事情,我去查看了 Microsoft 套接字库,并尝试根据合理的内容构建我自己的服务。仍然没有任何效果。如果您知道任何书籍、资源、有任何建议等,将不胜感激您能给我的任何帮助。感谢您的协助。

您将在下面找到我的代码。在这一点上,我所关心的就是在客户端和服务器之间建立连接。我可以回去弄清楚其余部分并从那里调整代码。

迈克

这是我一直在玩的服务器代码:

Imports System.Net.Sockets
Imports System.Net
Imports System.Text

Public Class BackupService

Private Mythread As Threading.Thread
Private clientThread As Threading.Thread
Private listener As New TcpListener(IPAddress.Parse("#.#.#.252"), 8888)



Protected Overrides Sub OnStart(ByVal args() As String)
' Add code here to start your service. This method should set things
' in motion so your service can do its work.

listener.Start() 'Listener for clients
System.IO.File.WriteAllText("C:\test\listener.txt", My.Computer.Clock.LocalTime)
Mythread = New Threading.Thread(AddressOf listenerLoop)
Mythread.Start()

End Sub

Protected Overrides Sub OnStop()
' Add code here to perform any tear-down necessary to stop your service.
Mythread.Abort()
End Sub

Protected Sub listenerLoop()

Dim client As TcpClient = listener.AcceptTcpClient()
Dim networkStream As NetworkStream = client.GetStream
Dim bytes(client.ReceiveBufferSize) As Byte
Dim dataReceived As String


While True
networkStream.Read(bytes, 0, CInt(client.ReceiveBufferSize)) 'Receives data from client and stores it into bytes
dataReceived = Encoding.ASCII.GetString(bytes) 'Encodes the data to ASCII standard
System.IO.File.AppendAllText("C:\test\listener.txt", dataReceived) 'Copies information to text file
Threading.Thread.Sleep(1000)

End While




'Listening for incoming connections
'While True
' If (listener.Pending = False) Then
' System.IO.File.AppendAllText("C:\test\listener.txt", "Sorry, no connection requests have arrived")
' Else
' 'Finds Incoming message and creates a thread for the client-server to pass information'
' clientThread = New Threading.Thread(AddressOf clientConnection)
' clientThread.Start()

' End If
' Threading.Thread.Sleep(1000) 'Let loop/thread sleep for 1 second to allow other processing and waits for clients
'End While
End Sub

'Protected Sub clientConnection()
' Dim client As TcpClient = listener.AcceptTcpClient()
' Dim networkStream As NetworkStream = client.GetStream
' Dim bytes(client.ReceiveBufferSize) As Byte
' Dim dataReceived As String
' Dim datasent As Boolean = False

' While datasent = False 'Continuously loops looking for sent data
' If (networkStream.CanRead = True) Then
' networkStream.Read(bytes, 0, CInt(client.ReceiveBufferSize)) 'Receives data from client and stores it into bytes
' dataReceived = Encoding.ASCII.GetString(bytes) 'Encodes the data to ASCII standard
' System.IO.File.AppendAllText("C:\test\listener.txt", dataReceived) 'Copies information to text file
' datasent = True
' End If
' Threading.Thread.Sleep(1000)
' End While

' networkStream.Close() 'Closes the network stream
' client.Close() 'Closes the client
' clientThread.Abort() 'Kills the the current thread

'End Sub
End Class

客户端代码(服务):

Imports System.Net.Sockets
Imports System.Net
Imports System.Text
Public Class TestWindowsService

Dim Mythread As Threading.Thread

Protected Overrides Sub OnStart(ByVal args() As String)
' Add code here to start your service. This method should set things
' in motion so your service can do its work.


'clientCommunication()


Mythread = New Threading.Thread(AddressOf KeepCounting)
Mythread.Start()
End Sub

Protected Overrides Sub OnStop()
' Add code here to perform any tear-down necessary to stop your service.

Mythread.Abort()
End Sub

'Protected Sub KeepCounting()
' Dim wait As Integer = 0
' Dim hour As Integer = 0
' Dim min As Integer = 0

' System.IO.File.WriteAllText("C:\test\StartTime.txt", "Start Time: " & My.Computer.Clock.LocalTime)


' Do While True

' hour = My.Computer.Clock.LocalTime.Hour

' If (hour = 1) Then
' min = (My.Computer.Clock.LocalTime.Minute * 60) + 60000
' Threading.Thread.Sleep(min) 'Sleeps for the number of minutes till 2am
' file.FileTime()
' Else
' Threading.Thread.Sleep(3600000) 'Sleeps for 1 hour
' System.IO.File.WriteAllText("C:\test\hourCheck\ThreadTime.txt", "Time: " & My.Computer.Clock.LocalTime)

' End If

' Loop

'End Sub

Protected Sub KeepCounting()
Dim tcpClient As New System.Net.Sockets.TcpClient()
tcpClient.Connect(IPAddress.Parse("#.#.#.11"), 8000)
Dim networkStream As NetworkStream = tcpClient.GetStream()

If networkStream.CanWrite And networkStream.CanRead Then

' Do a simple write.
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("Is anybody there")
networkStream.Write(sendBytes, 0, sendBytes.Length)

' Read the NetworkStream into a byte buffer.
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))

' Output the data received from the host to the console.
Dim returndata As String = Encoding.ASCII.GetString(bytes)
Console.WriteLine(("Host returned: " + returndata))


Else
If Not networkStream.CanRead Then
Console.WriteLine("cannot not write data to this stream")
tcpClient.Close()
Else
If Not networkStream.CanWrite Then
Console.WriteLine("cannot read data from this stream")
tcpClient.Close()
End If
End If
End If
' pause so user can view the console output
Console.ReadLine()


End Sub

End Class

客户端代码(扩展模块)

Imports System.Net.Sockets
Imports System.Net
Imports System.Text

Module Client_TCP_Communication

Public Sub clientCommunication()
Dim tcpClient As New System.Net.Sockets.TcpClient()
tcpClient.Connect("127.0.0.1", 8000)
Dim networkStream As NetworkStream = tcpClient.GetStream()

If networkStream.CanWrite And networkStream.CanRead Then

' Do a simple write.
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("Is anybody there")
networkStream.Write(sendBytes, 0, sendBytes.Length)

' Read the NetworkStream into a byte buffer.
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))

' Output the data received from the host to the console.
Dim returndata As String = Encoding.ASCII.GetString(bytes)
Console.WriteLine(("Host returned: " + returndata))


Else
If Not networkStream.CanRead Then
Console.WriteLine("cannot not write data to this stream")
tcpClient.Close()
Else
If Not networkStream.CanWrite Then
Console.WriteLine("cannot read data from this stream")
tcpClient.Close()
End If
End If
End If
' pause so user can view the console output
Console.ReadLine()





'Dim clientSocket As New System.Net.Sockets.TcpClient()
'Dim serverStream As NetworkStream

'While True
' serverStream = clientSocket.GetStream()
' Dim outStream As Byte() = System.Text.Encoding.ASCII.GetBytes("Message from client$")
' Dim inStream(1024) As Byte
' Dim returnData As String

' System.IO.File.WriteAllText("C:\test\client\ClientStarted.txt", "Time: " & My.Computer.Clock.LocalTime)
' clientSocket.Connect(IPAddress.Parse("#.#.#.11"), 8999)
' System.IO.File.WriteAllText("C:\test\client\ClientConnected.txt", "Time: " & My.Computer.Clock.LocalTime)

' serverStream.Write(outStream, 0, outStream.Length)
' serverStream.Flush()

' serverStream.Read(inStream, 0, CInt(clientSocket.ReceiveBufferSize))
' returnData = System.Text.Encoding.ASCII.GetString(inStream)
' System.IO.File.WriteAllText("C:\test\client\returnData.txt", "Time: " & returnData)

'End While

End Sub

End Module

最佳答案

要找出它启动然后停止的原因,您可以在尝试启动该服务后尝试查看应用程序事件日志。可能在启动时(或刚刚启动后)遇到导致服务停止的错误。

我在尝试编写类似服务时遇到了这个问题——在我的例子中,我试图自动检测要使用的 IP 地址,但结果是它无意中选择了我的 IPv6 环回地址并且绑定(bind)失败。事件日志中的一个错误为我提示了这一点。

关于windows - VB.net 服务编程和使用 TCP 套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10608062/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com