In this article, let us discuss how to write Perl socket programming using the inbuilt socket modules in Perl.
Perl socket modules provides an object interface that makes it easier to create and use TCP / UPD sockets.
本文讨论使用Perl内建的socket模块来实现Perl socket编程

This article covers the following topics:
本文的主题如下:
. Perl example code for TCP client and server             (Perl实现TCP客户端和服务端)
. Perl example code for UDP client and server             (Perl实现UDP客户端和服务端)
. Read and write descriptor list using Select(IO::Select) (使用select来读写描述符列表)

CPAN module IO::Socket::INET is used to perform socket operations such as 
— creating, binding, connecting, listening and closing the socket.
IO::Select module is used for obtaining the descriptors that are ready for read/write operations.
IO::Socket::INET用来执行socket操作,如创建,绑定,连接,监听,和关闭socket;
IO::Select模块用来获得可读/写操作的描述符;

Perl TCP Client and Server
TCP is a connection oriented networking protocol. 
In this example, let us review the Perl code-snippet that will explaining us the simple client and server communication.

Perl TCP Server Operation
Perl TCP 服务端操作
The socket operation such as socket creation, binding and listening to the socket is performed by the IO::Socket::INET module.

The Perl code given below does the following:
. Create the Socket                           (创建socket)
. Bind the socket to an address and port      (绑定socket的地址和端口)
. Listen to the socket at the port address    (监听端口)
. Accept the client connections               (接受连接)
. Perform read/write operation on the socket. (执行读写操作)

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

use IO::Socket::INET;

# flush after every write
$| = 1;

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 => '5000',
    Proto => 'tcp',
    Listen => 5,
    Reuse => 1
) or die "ERROR in Socket Creation : $!\n”;

print "SERVER Waiting for client connection on port 5000";

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 : $peeraddress, $peerport\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);

# 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”;
}

$socket->close();

Also, refer to our earlier Perl debugger article to learn how to debug your perl code.

Perl TCP Client Operation
Perl TCP 客户端操作
The Perl code given below does the following:
. Create the socket.                                 (创建socket) 
. Connect to the remote machine at a specific port.  (连接服务端的端口)
. Perform read/write operation on the socket.        (执行读/写操作)

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

use IO::Socket::INET;

# flush after every write
$| = 1;

my ($socket,$client_socket);

# creating object interface of IO::Socket::INET modules which internally creates
# socket, binds and connects to the TCP server running on the specific port.
$socket = new IO::Socket::INET (
    PeerHost => '127.0.0.1',
    PeerPort => '5000',
    Proto => 'tcp',
) or die "ERROR in Socket Creation : $!\n”;

print “TCP Connection Success.\n”;

# read the socket data sent by server.
$data = <$socket>;

# we can also read from socket through recv()  in IO::Socket::INET
# $socket->recv($data,1024);
print “Received from Server : $data\n”;

# write on the socket to server.
$data = “DATA from Client”;
print $socket “$data\n”;

# we can also send the data through IO::Socket::INET module,
# $socket->send($data);

sleep (10);
$socket->close();

Note: You can use Vim editor as a Perl IDE using the perl-support.vim Plugin.

Perl UDP Server
Perl UDP 服务端
The Perl code given below does the following:
. Create the socket.                     (创建socket) 
. Bind the socket to the specific port.  (绑定端口)

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

use IO::Socket::INET;

# flush after every write
$| = 1;

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

#  we call IO::Socket::INET->new() to create the UDP Socket and bound
# to specific port number mentioned in LocalPort and there is no need to provide
# LocalAddr explicitly as in TCPServer.
$socket = new IO::Socket::INET (
    LocalPort => '5000',
    Proto => 'udp',
) or die "ERROR in Socket Creation : $!\n”;

while(1)
{
  # read operation on the socket
  $socket->recv($recieved_data,1024);

#get the peerhost and peerport at which the recent data received.
  $peer_address = $socket->peerhost();
  $peer_port = $socket->peerport();
  print "\n($peer_address , $peer_port) said : $recieved_data";

#send the data to the client at which the read/write operations done recently.
  $data = “data from server\n”;
  print $socket “$data”;
}

$socket->close();

Perl UDP Client
Perl UDP 客户端
The Perl code given below does the following:
. Create the UDP client.                          (创建socket) 
. Connect to the specific UDP server.             (连接到指定UDP服务端)
. Perform write and read operation on the socket. (执行读/写操作)

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

use IO::Socket::INET;

# flush after every write
$| = 1;

my ($socket,$data);

# We call IO::Socket::INET->new() to create the UDP Socket
# and bind with the PeerAddr.
$socket = new IO::Socket::INET (
    PeerAddr   => '127.0.0.1:5000',
    Proto        => 'udp'
) or die "ERROR in Socket Creation : $!\n”;

#send operation
$data = “data from client”;
$socket->send($data);

#read operation
$data = <$socket>;
print “Data received from socket : $data\n ”;

sleep(10);
$socket->close();

Also, refer to our earlier article to understand Perl Array Reference.

IO::Select Module – Get to know the list of ready descriptors
IO::Select Module – 获得准备好的描述符

IO::Select module provides following two major functions:
. can_read() returns the available read descriptors   (返回可读的描述符) 
. can_write() returns the available write descriptors (返回可写的描述符)

To understand the usage of IO::Select, we are going to use this module in the tcpserver code.

Step 1 : Create the IO::Socket object interface
创建 IO::Socket对象接口

The following code-snippet creates the object interface of IO::Socket::INET modules 
which internally creates a socket, binds and listens to a specified port address.

$socket = new IO::Socket::INET (
    LocalHost => '127.0.0.1',
    LocalPort => '5000',
    Proto => 'tcp',
    Listen => 5,
    Reuse => 1
) or die "ERROR in Socket Creation : $!\n";

$select = IO::Select->new($socket) or die "IO::Select $!";

Step 2 : Add descriptors to Select objects
将描述符添加到Select对象

The following code-snippet adds the descriptor to the list of select objects to get the descriptors ready.

@ready_clients = $select->can_read(0);
foreach my $fh (@ready_clients)  {
  print $fh "";
  if($fh == $socket) {
    my $new = $socket->accept();
    $select->add($new);
  }
}

Step 3: Get descriptors which are ready to read
获得可读的描述符

Following Perl code-snippets gets the list of descriptor that are ready to read.

@ready_clients = $select->can_read(0);
foreach my $fh (@ready_clients)  {
  if($fh != $socket)  {
    chomp($data=<$socket>);
    print $data,"\n";
  }
}

In the same way, we can do for the write operation on the socket.

Step 4: Remove Client Socket Descriptor from Select list
将客户端socket描述符从select列表中删除

When the connection is closed, you can remove the client socket descriptor for the select list as shown below.
当连接关闭后,需要将socket描述符从select列表中删除

SIGPIPE signal gets generated when we try to send/receive data on the socket that is closed by the remote machine. 
So, we can assign the signal handler for SIGPIPE signal, which should remove of descriptor from the select list as shown below.
在使用socket进行数据的发送/接收中,当远端机器关闭socket连接时,将会发送SIGIPE信号.
因此,我们可以在收到SIGIPE信号时,将描述符从select 列表中删除

# $current_client is the global variable which has the recent file descriptor
# on which the send/receive operation is tried.
### Handle the PIPE
$SIG{PIPE} =  sub
{
  ####If we receieved SIGPIPE signal then call Disconnect this client function
  print "Received SIGPIPE , removing a client..\n";
  unless(defined $current_client){
    print "No clients to remove!\n";
  }else{
    $Select->remove($current_client);
    $current_client->close;
  }

#print Dumper $Self->Select->handles;
  print "Total connected clients =>".(($Select->count)-1)."<\n";
};

PERL 使用IO::Socket::INET模块实现socket编程相关推荐

  1. day8 动态导入模块、socket进阶

    文章目录 1. 动态导入模块 2. socket 进阶 1. 动态导入模块 文件目录如下: aa.py 文件中: class C(object):def __init__(self):self.nam ...

  2. python的socket模块_Python socket模块方法实现详解

    这篇文章主要介绍了python socket模块方法实现详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 socket ssh (不带防止粘包的方 ...

  3. java 网络io详解_Java网络socket编程详解

    或许有点长 但是一步步教你 我想你也愿意看7.2面向套接字编程 我们已经通过了解Socket的接口,知其所以然,下面我们就将通过具体的案例,来熟悉Socket的具体工作方式7.2.1使用套接字实现基于 ...

  4. php socket多人聊天,socket.io实现多人聊天

    1. 后端环境搭建 # npm init # npm install -s express # npm install -s socket.io npm init 会生成json文件作为依赖包,exp ...

  5. socket模块实现socket协议

    python内置模块socket模块可解决基于tcp和ucp协议的网络传输 一:基于udp协议进行网络传输 例1 : server端: import socket sk = socket.socket ...

  6. perl中的几个模块使用.

    perlCPAN模块DBI.DBD::Mysql my $db_host = "localhost"; my $db_port = "3306"; my $db ...

  7. Java进阶 | IO流核心模块与基本原理

    一.IO流与系统 IO技术在JDK中算是极其复杂的模块,其复杂的一个关键原因就是IO操作和系统内核的关联性,另外网络编程,文件管理都依赖IO技术,而且都是编程的难点,想要整体理解IO流,先从Linux ...

  8. java socket远空_JAVA Socket超时浅析

    套接字或插座(socket)是一种软件形式的抽象,用于表达两台机器间一个连接的"终端".针对一个特定的连接,每台机器上都有一个"套接字",可以想象它们之间有一条 ...

  9. 面试官:请讲一讲IO流核心模块与基本原理是什么?

    前言 一.IO流与系统 IO技术在JDK中算是极其复杂的模块,其复杂的一个关键原因就是IO操作和系统内核的关联性,另外网络编程,文件管理都依赖IO技术,而且都是编程的难点,想要整体理解IO流,先从Li ...

最新文章

  1. linux cuda 异常退出,cudaErrorCudartUnloading问题排查及建议方案
  2. dm-haiku 用法
  3. OpenStack 的部署T版(二)——Keystone组件
  4. 2021年陕西高考成绩单招查询时间,2021年陕西单招考试时间是什么时候,单招考试分数线是多少...
  5. 跳转到系统挑选铃声的页面
  6. 一个按钮多个ajax,如何为表格中的多个按钮设置AJAX调用
  7. iOS 不能播放远程视频(Android 可以)的问题
  8. 【JavaScript】JavaScript模拟实现面向对象一张图帮助你深刻理解原型链和原型对象
  9. android集成sdk 马甲包,Android配置马甲包
  10. 最好听的男孩名字及1000个好听的女孩的名字
  11. 什么是机器学习,为什么它如此重要?
  12. oracle 12c导入dmp文件(实践)
  13. java 支付宝退款批次号生成
  14. 用mysql触发器做数据统计
  15. 转载]“不能打开暂存盘文件,因为该文件已锁定”解决办法
  16. 专利与论文-2:什么是专利?专利的几种类型?
  17. 这个绿色才是2022的流量密码
  18. 解决百度地图移动端(微信浏览器等)拖拽事件和点击事件冲突的BUG
  19. 蜜罐php,PHP表单 – 带验证蜜罐
  20. 思科4500R系列交换机双引擎冗余讲解

热门文章

  1. iOS开发 - 动画实践系列
  2. springboot 常用插件
  3. 监听短信增删以及短信会话增删
  4. 注重IT的全程管控 第三方监理可有效保证IT质量
  5. Oracle 10g新特性——正则表达式(转)
  6. 2021年十大 web hacking 技术汇总
  7. 十万个为什么之为什么大家都说dubbo
  8. 前端自动化构建工具之webpack入门——简单入门
  9. 从“No space left on device”到删除海量文件
  10. thinkphp 手机号和用户名同时登录