Socket between Java and Perl

Socket is very useful in the communication between the processes in the same computer orin the network.

This is a simple example of a socket between Java and Perl. If you want to see the test,you can just start the requester.java as we will call the Perl server in the requester.

It is a little bit more difficult than our previous examples in Java or in Perl.Because the information sent by Java is stored in byte and Perl can read it,but in the other way, the information sent by Perl can’t be read directly inJava. Here I adopt this idea from StackOverflow. I implement the scanner library of Java which is standard Java library.

 

If you wantto use another way, you can find some propositions here.

Useful link:

http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string?rq=1

 

The Perlpart doesn’t change much, while in Java part we implement scanner.

We implement a thread.sleep(1000) because the Perl server needs times to start. If it shows that the server is not ready, you can retry and normally it will work.

 

 

Code:

Requester.java


package Socket2;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Requester {
	Socket requestSocket;
	OutputStream out;
	Scanner inp;
	String message;

	Requester() {}

	void run() {
		try {
			//1. creating a socket to connect to the server
			this.requestSocket = new Socket("localhost", 5002);
			System.out.println("Connected to localhost in port 5002");
			//2. get Input and Output streams
			this.out = this.requestSocket.getOutputStream();
			this.out.flush();
			this.inp = new Scanner(this.requestSocket.getInputStream())
					.useDelimiter("\\n");

			try {

				this.message = this.inp.hasNext() ? this.inp.next() : "";
				System.out.println("server>" + this.message);
				sendMessage("Hi my server\n");

				this.message = this.inp.hasNext() ? this.inp.next() : "";
				System.out.println("server>" + this.message);

				this.message = this.inp.hasNext() ? this.inp.next() : "";
				System.out.println("server>" + this.message);

				this.message = this.inp.hasNext() ? this.inp.next() : "";
				System.out.println("server>" + this.message);

			} catch (Exception e) {
				System.err.println("data received in unknown format");
			}

		} catch (UnknownHostException unknownHost) {
			System.err.println("You are trying to connect to an unknown host!");
		} catch (IOException ioException) {
			ioException.printStackTrace();

		} finally {
			//4: Closing connection
			try {
				this.inp.close();
				this.out.close();
				this.requestSocket.close();
			} catch (IOException ioException) {
				ioException.printStackTrace();
			}
		}
	}

	void sendMessage(final String msg) {
		try {

			this.out.write(msg.getBytes());
			this.out.flush();
			System.out.println("client>" + msg);
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

	public static void main(final String args[]) throws IOException {
		Process proc = null;

		try {
			proc = Runtime.getRuntime().exec(
					"cmd /C start perl C:\\Perl516\\PlServer.pl");//You need to put the PerlServer.pl in the C:\\Perl516
			//proc = Runtime.getRuntime().exec("cmd /C start PerlServer.bat");  //You need to put the PerlServer.bat in the same file as the Requester.java
			//proc = Runtime.getRuntime().exec("cmd /C start perl PlServer.pl"); //You need to put the PlServer.pl in the same file as the Requester.java
			proc.waitFor();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (proc.exitValue() == 0) {
			System.out.println("Server Start");

		} else {
			System.out.println("Server can't start");
		}

		Requester client = new Requester();
		client.run();
	}
}

PlServer.pl


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

use IO::Socket::INET;

# flush after every write
$| = 1;
$num =0;

my ($socket,$client_socket);
my ($peeraddress,$peerport);

# creating object interface of IO::Socket::INET modules which internally does
# socket creation, binding and listening at the specified port address.
$socket = new IO::Socket::INET (
LocalHost => '127.0.0.1',
LocalPort => '5002',
Proto => 'tcp',
Listen => 5,
Reuse => 1
) or die "ERROR in Socket Creation : $!\n";

print "SERVER Waiting for client connection on port 5002\n";

#Here we use loop infinite, so 1 is a condition which is always true.
#while(1)
#{


# waiting for new client connection.
$client_socket = $socket->accept();

# get the host and port number of newly connected client.
$peer_address = $client_socket->peerhost();
$peer_port = $client_socket->peerport();



print "Accepted New Client Connection From : $peer_address, $peer_port \n ";



# write operation on the newly accepted client.
$data = "DATA from Server";
print $client_socket "$data\n";
# we can also send the data through IO::Socket::INET module,
# $client_socket->send($data);
$num++;

# read operation on the newly accepted client
$data = <$client_socket>;
# we can also read from socket through recv()  in IO::Socket::INET
# $client_socket->recv($data,1024);
print "Received from Client : $data\n";


# write operation on the newly accepted client.
$data = "Bye";
print $client_socket "$data\n";
# we can also send the data through IO::Socket::INET module,
# $client_socket->send($data);
$num++;

$num--;
# write operation on the newly accepted client.
print $client_socket "received message number $num\n";
# we can also send the data through IO::Socket::INET module,
# $client_socket->send($data);


$socket->close();
<>;





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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值