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

编程入门 行业动态 更新时间:2024-10-28 17:19:04
本文介绍了VB 服务编程和使用 TCP 套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

I am having a problem and I was curious if anyone could help me solve it. I took a tutorial for client-server socket programming for VB.NET. I then tried to implement it using a service rather than a program. I understand how it works as a program, but when I try to port it over to a service it doesn't work. When I run the service it starts and stops instantly. It never makes a connection. Unfortunately, I am not that great of VB programmer but so far I am liking it a lot for rapid development of programs.

这项服务的理念是:

在计算机启动时运行获取 PC 的名称

将PC的名称发送到服务器 run when the computer starts grab the name of the PC

Send the name of the PC to the server

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

a. the server then takes the name and looks it up in a database

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

b. returns the time that the client machine is suppose to back up

然后客户端机器计算当前时间和它应该备份的时间.把所有东西都放在 ms 中.

The client machine then does the math for the current time and the time it’s suppose to backup & put everything in ms.

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

Now to answer a question that I have found common in the forums. Why don't I use task scheduler. Well I did use task schedule and had the server control times to machines that way. However, some computers will go into a dormant state, I would say this dormant state affects 20% of the machines. No this dormant state is not sleep mode and not hibernation. The computers are on and they are react very quickly to mouse movement. I created a service that writes the time to a file on the C:\ and this has always worked. So now I have decided to have a service on the client machine and have it communicate with the server.

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

I have collected very little information about creating service and network socket programming. Unfortunately, I haven’t found anything that ties the 2 together. I found a vb client-server program that does what I want, but I want it as a service not a program. I found a temporary solution with creating files using PSEXEC from the server, but this process is just so umm unsophisticated.

我做了下一个最好的事情,我去检查了微软的套接字库,并试图根据有意义的东西构建我自己的服务.仍然没有任何作用.如果您知道任何书籍、资源、有任何建议等,您能给我的任何帮助将不胜感激.感谢您的帮助.

I did the next best thing and I went and reviewed the Microsoft library for sockets and tried to build my own service based on what makes sense. Still nothing works. If you know of any books, resources, have any advice, etc. any help you can give me will be greatly appreciated. Thank you for your assistance.

您会在下面找到我的代码.在这一点上,我关心的只是在客户端和服务器之间建立连接.我可以回去弄清楚剩下的部分,然后从那里重新编写代码.

Below you will find my code. At this point all I care about doing is making the connections between clients and the server. I can go back to figuring out the rest and tweek the code from there.

迈克

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

Here is the server code I have been playing with:

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

客户端代码(扩展模块)

Client Code (extended Module)

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

推荐答案

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

To find out why it's starting and then stopping, you might try looking in the Application event log after trying to start the service. Could be running into an error on (or just after) startup that is causing the service to stop.

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

I ran into that problem when trying to write a similar service--in my case I was trying to auto-detect the IP address to use, and it turns out it was inadvertently selecting my IPv6 loopback address and failing to bind. An error in the event log hinted at this for me.

这篇关于VB 服务编程和使用 TCP 套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 08:38:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1406784.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:VB   net   TCP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!