Named pipe between Java and Perl

来源:互联网 发布:mac隐藏磁盘 编辑:程序博客网 时间:2024/05/11 12:32

There arenot only one way to fulfil the functions of communication between Java andPerl. Except for the socket, named pipe is also a possible solution. Actuallymy tutor has implemented the first version with named pipe in C# and Perl.

This is asimple graph I made to explain the IPC:

There are 2kinds of pipe: anonymous pipe and named pipe.

Anonymous pipe: Pipe is created when the process is opened andis terminated when the process is closed. So it is less secured.

Named pipe: It is independent of the process. So we canterminate the pipe during the process which is safer.

 

So why do Ichoose socket but not named pipe? The most important reason is that there is nonamed pipe library in Java. But we can create it in Perl and consume it inJava.

In terms ofthe quality, I made a basic comparison between named pipe and socket. 



For ourproject, the speed factor is not very important as the information sent issimply some messages. So at last we choose socket.

 

This is asimple example of named pipe communication between Java and Perl. If you wantto see the test, you can just start the requester.java as we will call the Perlserver in the requester.

 

Useful link:

http://stackoverflow.com/questions/4974989/concurrent-read-write-of-named-pipe-in-java-on-windows

 

The Perlpart is not special, while in Java part we need to find the pipe file andconsume it.


Code:

 Pipe1.java 


package pipe;import java.io.IOException;import java.io.RandomAccessFile;public class pipe1{/** * @param args * @throws IOException */public static void main(String args[]) throws IOException {try {// Connect to the pipeRandomAccessFile pipe = new RandomAccessFile("\\\\.\\pipe\\pipe1", "rw");System.out.println("Client connected");String echoText = "Hi server! This is Client!\n";        // read response        System.out.println("Response: " + pipe.readLine());// write to pipepipe.write ( echoText.getBytes() );pipe.close();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

PipeServer.pl

#!/usr/bin/perl#perlPipe.pluse Win32::Pipe;#create pipe$Pipe = new Win32::Pipe("pipe1")|| die "Can't Create Named Pipe\n";#pipe connectionprint "SERVER Waiting for client connection\n";$Result = $Pipe->Connect();print "SERVER connected\n";#write data to the pipe$Result = $Pipe->Write("Hi client. This is Server!\n");#receive and print data from the pipe$Data = $Pipe->Read();print $Data;$Pipe->Disconnect();




原创粉丝点击