简体   繁体   中英

inter-process communication on local machine using socket in perl and c#

I am working on ac# application that spawn new Processes to run Perl programs:

I was wondering if there is a way to use socket interface to let perl program to talk to c# application. If using socket, the address has to be local host: 127.0.0.1? How to choose which port number to use?

also,

Since the C# application spawn a Process to run Perl program, is there a way to use inter-process communication in c# to achieve this task? I mean maybe the process that is running the perl can send a message to the c# appilication?

Thanks.

Use the IO::Socket::INET module.

You can connect to a port on localhost

$sock = IO::Socket::INET->new('127.0.0.1:2525');

or to another address

$sock = IO::Socket::INET->new("host.example.com:6789");

These examples assume the Perl program will be the client and you've written the server in C#. If it's the other way around, use the IO::Select module. Below is an example from its documentation:

use IO::Select;
use IO::Socket;

$lsn = new IO::Socket::INET(Listen => 1, LocalPort => 8080);
$sel = new IO::Select( $lsn );

while (@ready = $sel->can_read) {
    foreach $fh (@ready) {
        if ($fh == $lsn) {
            # Create a new socket
            $new = $lsn->accept;
            $sel->add($new);
        }
        else {
            # Process socket
            # Maybe we have finished with the socket
            $sel->remove($fh);
            $fh->close;
        }
    }
}

Using this code, you'd then connect from C# to port 8080 on the localhost.

The choice of port is mostly arbitrary. Both sides need to agree on the rendezvous port, and you want to avoid ports below 1024. Whether you connect to localhost or another address is determined by the address to which the server is bound. To bind to a network-accessible address, modify the above code to use

$lsn = new IO::Socket::INET(Listen => 1, LocalAddr => "host.example.com:8080");

The backlog of size 1 (the Listen parameter) is unusual. A typical size is the value of SOMAXCONN from sys/socket.h .

您可以尝试命名管道(.NET侧为System.IO.Pipes,Perl侧为Win32 :: Pipe)。

Your best option is a socket. You can choose any port that is not in use, and is above 1024. But you might want to review a list of common port assignments just to make sure you don't choose a conflict with a program you have in your environment.

-- Edit:

It seems that link advises port numbers above 49152. Wow, times change :)

您可以在没有套接字和管道的情况下进行管理:在C#中,重定向生成的进程的标准输入和输出( 例如 ),然后编写perl脚本,该脚本从STDIN接收数据并将结果发送到STDOUT。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM