Named pipe between Java and Perl

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 pipe
		RandomAccessFile 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 pipe
		pipe.write ( echoText.getBytes() );
	
		pipe.close();

		} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		}
}
}

PipeServer.pl

#!/usr/bin/perl
#perlPipe.pl

use Win32::Pipe;
#create pipe
$Pipe = new Win32::Pipe("pipe1")|| die "Can't Create Named Pipe\n";

#pipe connection
print "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();




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值