How to open a Windows named pipe from Java?

本小妞迷上赌 提交于 2019-12-27 11:42:12

问题


On our Linux system we use named pipes for interprocess communication (a producer and a consumer).

In order to test the consumer (Java) code, I would like to implement (in Java) a dummy producer which writes to a named pipe which is connected to the consumer.

Now the test should also work in the Windows development environment. Thus I would like to know how to create a named pipe in Windows from Java. In Linux I can use mkfifo (called using Runtime.exec() ), but how should I do this on Windows?


回答1:


Use Named Pipes to Communicate Between Java and .Net Processes

Relevant part in the link

try {
  // Connect to the pipe
  RandomAccessFile pipe = new RandomAccessFile("\\\\.\\pipe\\testpipe", "rw");
  String echoText = "Hello word\n";
  // write to pipe
  pipe.write ( echoText.getBytes() );
  // read response
  String echoResponse = pipe.readLine();
  System.out.println("Response: " + echoResponse );
  pipe.close();
} catch (Exception e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}



回答2:


In windows, named pipes exist but they cannot be created as files in a writeable filesystem and there is no command line tool. They live in a special filesystem and can be created only by using the Win32 API.

Looks like you'll have to resort to native code, or switch from pipes to sockets for IPC - probably the best longterm solution, since it's much more portable.




回答3:


You can create named pipe using JNA library https://github.com/java-native-access/jna

It is clearly shown in the following test: https://github.com/java-native-access/jna/blob/master/contrib/platform/test/com/sun/jna/platform/win32/Kernel32NamedPipeTest.java

API of JNA wrapper is the same as Win32 hence you will be able to use all the features and power of named pipes on Windows.




回答4:


It is very much possible to read and write to an existing named pipe in Java. You cannot, to my knowledge, create a named pipe in a Windows environment. Linux is a different story as named pipes can be created and consumed like files.

Relevant link on interacting with an existing pipe: http://v01ver-howto.blogspot.com/2010/04/howto-use-named-pipes-to-communicate.html




回答5:


maybe could use cygwin named pipes--if all your processes are cygwin.



来源:https://stackoverflow.com/questions/634564/how-to-open-a-windows-named-pipe-from-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!