首页 > 系统相关 >powershell 作服务端 响应网络(socket tcp)连接 提供文件夹大小查询服务

powershell 作服务端 响应网络(socket tcp)连接 提供文件夹大小查询服务

时间:2023-12-21 23:00:13浏览次数:35  
标签:Verbose Stream tcp Port Write Client Path powershell socket

包含:

  • 端口占用检测
  • 心跳包网络断线检测
  • 传入的数据是否为合法有效的目录路径检测
  • 读取计算文件夹大小(不含软链接|symlink)
  • 传回查询到的文件夹大小
[cmdletbinding()] Param($Port = 8888)

$VerbosePreference = "Continue"
# 值或取`SilentlyContinue`,此时需调用脚本时传入`-Verbose`才等效`Continue`。
# `Continue`输出`Write-Verbose`的内容。

Write-Verbose("Check port {0} busy/available" -f $Port)
$Connection = Get-NetTCPConnection -LocalPort $Port -ErrorAction SilentlyContinue
if($Connection){
    if($Connection.OwningProcess.GetType().Name -eq "UInt32"){
        $Process_ID = $Connection.OwningProcess
    }
    else{
        $Process_ID = $Connection.OwningProcess[1]
        # `$Connection.OwningProcess`为数组对象(System.Object)
    }
    if($Process_ID){
        Write-Error("Port {0} is busy, using by process ID {1}." -f $Port, $Process_ID)
        Exit
    }
    else{
        Write-Verbose("Port {0} is available" -f $Port)
    }
}
else{
    Write-Verbose("Port {0} is available" -f $Port)
}
$Connection = $Null

$Listener = New-Object System.Net.Sockets.TcpListener -ArgumentList $Port
try{
    $Listener.Start()
    # 可能的异常:
    # # "通常每个套接字地址(协议/网络地址/端口)只允许使用一次。"
    # # CategoryInfo          : NotSpecified: (:) [], ParentContainsErrorRecordException
    # # FullyQualifiedErrorId : SocketException
    Write-Verbose("Start linsten")
}
catch {
    Write-Error("Linsten failed")
    throw
}

Write-Verbose "Server started"

While ($True) {
    Write-Host("Waiting connection from port {0}" -f $Port)

    $Socket_TCP_Client = $Listener.AcceptTcpClient()
    # incoming socket tcp client endpoint.
    
    $Client_Address = $Socket_TCP_Client.client.RemoteEndPoint.ToString()
	Write-Verbose ("New connection from {0}" -f $Client_Address)

	# Start-Sleep -Milliseconds 1000

	$Stream = $Socket_TCP_Client.GetStream()
    $Stream_Reader = [System.IO.StreamReader]::new($Stream)

    $Previous_Communication_Time = Get-Date -UFormat %s

	While ($True) {
        $string = $Null
        if($Stream.DataAvailable){# read content from stream, write to string.
            # ×<空数据亦会触发> 换行符会触发(但不代表空数据,只是换行符被作为控制符,剩余的数据为空)
		   
            Write-Verbose "Data available, read line"
            $string = $Stream_Reader.ReadLine()
            # 可能的异常
            # # 使用“0”个参数调用“ReadLine”时发生异常:“无法从传输连接中读取数据: 你的主机中的软件中止了一个已建立的连接。。”
             
            $Previous_Communication_Time = Get-Date -UFormat %s
        }
        else{
             Write-Verbose "Waiting data."
             Start-Sleep -Milliseconds 1000
        }
        if($string -eq "exit"){
            $Stream_Reader.Dispose()
            Write-Verbose "Stream_Reader.Dispose done"
            $Stream_Reader.Close()
            Write-Verbose "Stream_Reader.Close done"

            $Stream.Dispose()
            Write-Verbose "Stream.Dispose done"
            $Stream.Close()
            Write-Verbose "Stream.Close done"

            $Socket_TCP_Client.Dispose()
            Write-Verbose "Socket_TCP_Client.Dispose done"
            $Socket_TCP_Client.Close()
            Write-Verbose "Socket_TCP_Client.Close done"

            break
        }
        elseif ($string) {
            Write-Host("Message received from {0}:`n {1}" -f $Client_Address, $string)
            
            $Path = $string
            $string = $Null

            $Is_Path_Exist_Folder = $Null
            try{
                $Is_Path_Exist_Folder = Test-Path -Path $Path -PathType Container
                # 可能的异常:
                # # "Test-Path : 路径中具有非法字符。"
            }catch{}
            if($Is_Path_Exist_Folder){
                Write-Verbose "Path valid - Path is a folder"
            }
            else{
                Write-Verbose "Path invalid - Path is not a folder, skip"
            }

            if($Is_Path_Exist_Folder){
                Write-Verbose "Measure size (length) of folder.."
                $Command = 'Get-ChildItem -Path "'+ $Path + '" -Recurse | Measure-Object -Property Length -Sum'
                $GenericMeasureInfo = Invoke-Expression $Command
                $Size = $GenericMeasureInfo.Sum
                Write-Verbose("Folder size (length) is {0}" -f $Size)

			    $Bytes  = [text.Encoding]::Ascii.GetBytes($Size)
			    $string = $Null
			    
                Write-Verbose "Send size to client"
			    $Stream.Write($Bytes,0,$Bytes.length)
			    $Stream.Flush()
            }
            else{
                $Bytes  = [text.Encoding]::Ascii.GetBytes("-1")
                Write-Verbose "Send error code to client"
			    $Stream.Write($Bytes,0,$Bytes.length)
			    $Stream.Flush()
            }
		}
        ElseIf((($Current_Time = (Get-Date -UFormat %s)) - $Previous_Communication_Time) -gt 3){ #等待数据超时,检查断线
            $bytes = 0
            try{ #heart-beat
                Write-Verbose "Heart-beat test"
                $bytes  = [text.Encoding]::Ascii.GetBytes("`0")
                # 参见:[(16)Powershell中的转义字符 - yang-leo - 博客园](https://www.cnblogs.com/leoyang63/articles/12060596.html)
                $Stream.Write($bytes,0,$bytes.length)
			    $Stream.Flush()
                $Previous_Communication_Time = $Current_Time
                Write-Verbose("Connection {0} alive" -f $Client_Address)
            }catch{
                Write-Verbose("Connection {0} failed" -f $Client_Address)
                break
            }
        }
	}
    if($string -eq "exit"){
        break
    }else{
        Write-Host "Client disconnect"
    }
}

$Listener.Stop()
Write-Verbose "Listener.Stop done"
Write-Verbose "Server stopped"

Write-Host "Exit"
Exit

标签:Verbose,Stream,tcp,Port,Write,Client,Path,powershell,socket
From: https://www.cnblogs.com/RobertL/p/17920310.html

相关文章

  • Capture a TCP dump from a Linux node in an AKS cluster
    https://learn.microsoft.com/en-us/troubleshoot/azure/azure-kubernetes/capture-tcp-dump-linux-node-akshttps://learn.microsoft.com/en-us/azure/aks/node-access#create-an-interactive-shell-connection-to-a-linux-nodekubectlgetnodes-owidekubectldebugno......
  • 用Python进行websocket接口测试
    我们在做接口测试时,除了常见的http接口,还有一种比较多见,就是socket接口,今天讲解下怎么用Python进行websocket接口测试。现在大多数用的都是websocket,那我们就先来安装一下websocket的安装包。pipinstallwebsocket-client 安装完之后,我们就开始我们的websocket之旅了。我们先来看......
  • 出错处理封装函数 - 使Socket编程更安全可靠
    导语       在Socket编程中,错误处理是至关重要的一环。通过封装出错处理函数,我们可以提高代码的可读性和可维护性,增加代码的重用性,统一管理错误信息,提高系统的稳定性和可靠性。本文将详细介绍为什么要进行出错处理函数的封装,并探讨如何使Socket编程更加安全可靠。   正......
  • Socket.D 基于消息的响应式应用层网络协议
    首先根据Socket.D官网的副标题,Socket.D的自我定义是:基于事件和语义消息流的网络应用协议。官网定义的特点是:基于事件,每个消息都可事件路由所谓语义,通过元信息进行语义描述流关联性,有相关的消息会串成一个流语言无关,使用二进制输传数据(支持tcp,ws,udp)。支持多语言、......
  • Mysql以及TCP socket的C++代码
    在使用socket编写tcp的C++程序时,遇到了一个问题:那就bind冲突了,分析原因:是因为std中有bind函数,而socket中也有,但是没有报重复定义的错误,这就有一点难办了。百度了一下:发现只要使用::bind就可以调用socket的bind。下面把这个套接字socket的server端代码贴出来:staticvoid*serv......
  • websocket++
    一、介绍版本:WebSocket++(0.8.2)1、readme.md参照readme.mdWebSocket++是一个只有头文件(只有hpp文件)的c++库,它实现了RFC6455(WebSocket协议)。它允许将WebSocket客户端和服务端集成到c++程序中。它使用了可互换的网络传输模块,包括:基于原始字符缓冲区的模块基于c++的iostre......
  • 【网关开发】Openresty使用cosocket API 发送http与tcp网络请求
    背景为网关提供健康检查功能时需要对节点发送http或者tcp探活请求。Openresty提供cosocket来处理非阻塞IO。实现跟工程结合在一起,这里简单拼接数据结构localfunction__default_check_alive(status)returnstatus>=200andstatus<=299endlocalfunctiondebug_c......
  • Python语言实现两台计算机用TCP协议跨局域网通信
    成果展示:(这张图是在我本地电脑上用pycharm运行两个程序测试,实际可以在两台电脑上分别运行。)设备要求和实现的功能:实现的功能:跨局域网通信(仅支持两台计算机)跨局域网收发小文件,支持缓存在服务器,再一键接收(仅支持两台计算机)使用方法:在服务器上运行server.py程序,在两台客户......
  • WebSocket和Socket的区别
    区别总结协议不同Socket是基于传输层TCP协议的,而Websocket是基于HTTP协议的。Socket通信是通过Socket套接字来实现的,而Websocket通信是通过HTTP的握手过程实现的。持久化连接传统的Socket通信是基于短连接的,通信完成后即断开连接。Websocket将HTTP协议升......
  • 物联网架构实例—解决Linux(Ubuntu)服务器最大TCP连接数限制
    1.前言:在对物联网网关进行压测的时候,发现在腾讯云部署网关程序,设备接入数量只能达到4000多个长连接,之后就再也无法接入终端了。之前在阿里云部署的时候明明可以到达2万左右,而且腾讯云的这个服务器比阿里云的硬件配置还要高上不少,不至于那么差,随后查阅大量资料终于完美解决。2.解......