Клиентский именованный канал в Powershell не подключается к серверу в Java - PullRequest
1 голос
/ 02 апреля 2019

Я реализовал простой двунаправленный конвейерный сервер в Java с использованием JNA, соответственно, клиент в Powershell.

По сути, я ожидаю, что клиент подключится, отправит сообщение на сервер и, наконец, получит сообщение обратнос сервера.

Хотя фактические результаты отличаются.Когда я сначала запускаю сервер, а затем клиента, клиент всегда ждет подключения, а сервер подключается, а затем ожидает чтения сообщения из канала.

Код на Java для сервера, соответственно код в Powershell для клиента, можно увидеть ниже.

Есть идеи, как решить эту проблему?

Спасибо!

     static final int MAX_BUFFER_SIZE = 1024;

    static String pipeName = "\\\\.\\pipe\\testpipe";
    static HANDLE namedPipe;

    public static void main(final String[] args) {
        createPipe();
        runServerFile();
    }

    private static void createPipe() {
        namedPipe = INSTANCE.CreateNamedPipe(pipeName,
                WinBase.PIPE_ACCESS_DUPLEX ,        // dwOpenMode
                WinBase.PIPE_TYPE_BYTE | WinBase.PIPE_READMODE_BYTE | WinBase.PIPE_WAIT,// | WinBase.PIPE_READMODE_MESSAGE | WinBase.PIPE_TYPE_MESSAGE,    // dwPipeMode
                WinBase.PIPE_UNLIMITED_INSTANCES ,    // nMaxInstances,
                //WinBase.PIPE_UNLIMITED_INSTANCES,    // nMaxInstances (255),
                Byte.MAX_VALUE,    // nOutBufferSize,
                Byte.MAX_VALUE,    // nInBufferSize,
                1000,    // nDefaultTimeOut,
                null);    // lpSecurityAttributes

        System.out.println("Created pipe: " + namedPipe.toString() + " invalid_handle = " + WinBase.INVALID_HANDLE_VALUE.toString());
        System.out.println("Last error: " + Native.getLastError());
    }

    private static void runServerFile() {
        RandomAccessFile npipeClient = null;
        try {
            System.out.println("br1");


            npipeClient = new RandomAccessFile(pipeName, "rws");

            INSTANCE.ConnectNamedPipe(namedPipe,null);

            byte[] buffer = new byte[100];
            int rd_count;
            String recv;
            System.out.println("Connected pipe");

            do{
                System.out.println("Before read");

                rd_count = npipeClient.read(buffer);
                if(rd_count<0) break;
                System.out.println("After read");

                recv = new String(buffer,0, rd_count);
                System.out.println("Received" + recv);
            }while(!recv.equalsIgnoreCase("done"));
            System.out.println("Received correct message");

            //npipeClient.write("Hello world!".getBytes());
            npipeClient.writeUTF("Hello back!");
            //npipeClient.getFD().sync();
            //INSTANCE.FlushFileBuffers(new HANDLE(npipeClient.getFD().));
            System.out.println("Sent: Hello back");

            npipeClient.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
param ($ComputerName = '.')

$npipeClient = new-object System.IO.Pipes.NamedPipeClientStream($ComputerName, 'testpipe', [System.IO.Pipes.PipeDirection]::InOut,
                                                                [System.IO.Pipes.PipeOptions]::None, 
                                                                [System.Security.Principal.TokenImpersonationLevel]::Impersonation)
$pipeReader = $pipeWriter = $null

function WriteToPipeAndLog($msg) {
    $msg
    $pipeWriter.WriteLine($msg)
}

try {
    'Client connecting to sever'
    $npipeClient.Connect()
    'Connected to server'

    $pipeReader = new-object System.IO.StreamReader($npipeClient)
    $pipeWriter = new-object System.IO.StreamWriter($npipeClient)
    $pipeWriter.AutoFlush = $true

    Write-Host "Sent: Hello world!"
    $pipeWriter.WriteLine('Hello world!')
    $pipeWriter.WriteLine('How ya doing')
    $pipeWriter.WriteLine('Done')

    while (($line = $read.ReadLine()) -ne $null)
    {
       Write-Host "Received: "  $line
    }

}
finally {
    'Client exiting'
    $npipeClient.Dispose()
}



...