#!/usr/bin/perl use strict; use warnings; use IO::Socket::INET; use threads; use Net::MQTT::Simple; use POSIX qw(strftime); use Sys::Syslog qw(:DEFAULT :standard :macros); my $mqtt; my $client; my $ident='tcp-mqtt_server'; my $logopt='ndelay'; my $facility='LOG_USER'; my $th_id; my $topic; my $value; sub Main { $mqtt = Net::MQTT::Simple->new("localhost:1883"); openlog($ident, $logopt, $facility); # don't forget this # flush after every write $| = 1; my ( $socket, $client_socket ); # Bind to listening address and port $socket = new IO::Socket::INET ( LocalHost => '0.0.0.0', LocalPort => '1001', Proto => 'tcp', Listen => 5, Reuse => 1 ) or die "Could not open socket: ".$!."\n"; print "SERVER Waiting for client connections...\n"; syslog(LOG_INFO,"tcp-mqtt server starting"); my @clients = (); while(1) { # Waiting for new client connection. $client_socket = $socket->accept(); # Push new client connection to it's own thread push ( @clients, threads->create( \&clientHandler, $client_socket ) ); foreach ( @clients ) { if( $_->is_joinable() ) { $_->join(); } } } $socket->close(); return 1; } sub clientHandler { my ($client_socket) = @_; my %user = (); $user{peer_address} = $client_socket->peerhost(); $user{peer_port} = $client_socket->peerport(); $user{local_port} = $client_socket->sockport(); $th_id = threads->tid(); print "Client ".$user{peer_address}.":".$user{peer_port}.":".$user{local_port}."\n"; syslog(LOG_INFO,"Client $user{peer_address}:$user{peer_port}:$user{local_port}:$th_id is connected"); eval{ my $datestring = strftime "%a %b %e %H:%M:%S %Y", localtime; printf("$datestring\n"); print $client_socket "\n"; print $client_socket "VLIN\n"; while( my $buffer = <$client_socket> ) { print $buffer; my $value = substr $buffer, 0,-2; $mqtt->retain("minimon/VLIN" => $buffer); syslog(LOG_INFO,"VLIN: $buffer"); last; } sleep(300); }; if($@){ syslog(LOG_INFO,"tcp-mqtt exception:$@->getErrorMessage()"); } $client_socket->shutdown(2); #$client_socket->close(); print "Client exit from ".$user{peer_address}.":".$user{peer_port}."\n"; # Client has exited so thread should exit too threads->exit(); } # Start the Main loop Main();