radu has asked for the wisdom of the Perl Monks concerning the following question:
I'm trying to make a client server socket application because I want to change some communication apis based in PHP in a centos7 server that sadly now it becomes very slow, I made some tests with perl as I'm new with this language and I'm very glad with the results.
I successfuly made a script to parse some mail logs and import it to database for filtering purposes and I can say that it is by far the faster (in cpu resources) than other languages, but now, what I want to do is:
Actually I have in each server (more that 100 servers) with a php script that runs every minute and introduces some data to the central server api. At the begining it was great, very easy and was working fine in PHP but now I'm facing some issues related to php + big file reading and parsing, thing that is done great in perl.
I tested a simple script posted here that can handle multiple clients and do the job very good, but for some reason, sometimes the server brokes with aparently no error message and nothing to trace and as it will be used in production servers I don't want it to silently stop working.
When I connect to socket I can see server is accepting the request and do it all fine, but if I start to send data at sometime if I send a lot of data it breaks.
Here is the code I used:
Any help will be appreciated#!/usr/bin/perl use strict; use warnings; use threads; use IO::Socket::IP; my $host = '127.0.0.1'; my $port = '1337'; my $proto = 'tcp'; my $debug = 1; my $output = 'report.txt'; my @allowed_ips = ('127.0.0.1'); sub Main { # flush after every write $| = 1; my ($socket, $client_socket); # Bind to listening address and port $socket = new IO::Socket::INET( LocalHost => $host, LocalPort => $port, Proto => $proto, Listen => 5, Reuse => 1 ) or die "ERROR > Could not open socket: ".$!."\n"; print "INFO > Waiting for client connections on tcp:[$host]:$port +...\n"; 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_socke +t)); foreach(@clients){ if($_->is_joinable()) { $_->join(); } } } $socket->close(); return 1; } sub clientHandler { # Socket is passed to thread as first (and only) argument. my ($client_socket) = @_; # Create hash for user connection/session information and set init +ial connection information. my %user = (); $user{peer_address} = $client_socket->peerhost(); $user{peer_port} = $client_socket->peerport(); unless (client_allowed($user{peer_address})){ print $client_socket "Server > Connection denied.\n"; print "WARN > Connection from $user{peer_address}:$user{peer_ +port} denied by IP policy.\n"; $client_socket->shutdown(2); $client_socket->close(); threads->exit(); } print "INFO > Client ".$user{peer_address}.":".$user{peer_port}." + has been conected.\n"; # Let client know that server is ready for commands. print $client_socket "Server > Welcome to raClus-Server $user{peer +_address}\n$user{peer_address}> "; # Listen for commands while client socket remains open while(my $buffer = <$client_socket>){ # Accept the command `PING` from client with optional argument +s if($buffer =~ /^PING(\s|$)/i) { print $client_socket "Server > Pong!\n"; } # Accept the command `HELLO` from client with optional argumen +ts if($buffer =~ /^HELLO(\s|$)/i){ print $client_socket "Server > Hello!\n"; print $client_socket "Server > Your IP:\t".$user{peer_addr +ess}."\n"; print $client_socket "Server > Your Port:\t".$user{peer_po +rt}."\n"; } # This will terminate the client connection to the server if($buffer =~ /^QUIT(\s|$)/i){ # Print to client, and print to STDOUT then exit client co +nnection & thread print $client_socket "Server > GOODBYE\n"; print "INFO > Client ".$user{peer_address}.":".$user{peer +_port}." has been disconnected.\n"; $client_socket->shutdown(2); threads->exit(); } print "DEBUG > $buffer" if $debug; print $client_socket "$user{peer_address} > "; } print "INFO > Client ".$user{peer_address}.":".$user{peer_port}." + has been disconnected.\n"; # Client has exited so thread should exit too threads->exit(); } sub client_allowed { my $client_ip = shift; return grep { $_ eq $client_ip || $_ eq '0/0' || $_ eq '0.0.0.0/0' + } @allowed_ips; } # Start the Main loop Main();
Thanks!
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Client-Server app
by NetWallah (Canon) on Sep 27, 2018 at 17:17 UTC | |
Could you quantify "A lot of data" ? The only suspicious thing I see in the code is : Where you use a global (to the while loop) for $client_socket. I would rather see that as: and delete the global declaration. My thinking (Probably pretty low probability, unless a lot of clients attempt simultaneous connect) is that this may prevent a potential race condition where the content of $client_socket changes before the invoked thread has had a chance to copy it. Memory fault -- brain fried | [reply] [d/l] [select] |
by radu (Initiate) on Sep 28, 2018 at 06:08 UTC | |
Hello NetWallah, First of all, thanks for your answer. And about the "lot of data" I'm doing test with files of more or less 100k lines of log file. Usually the server will handle maxium 3-4 lines per connection and then parse it and update a table in mysql and log it to a csv file but I want it to be stable and dont break if any server do a full update of 10k-20k lines of logs I tried to delete the global declaration and declare it in the while(1) loop, but it still breaks with only 1 connection. If I try it with The problem I think is related to the writing on the log file, because if I comment the line that open the report file in append mode and write the buffer it breaks. Now I'm doing tests with 3 simultaneous clients sending 250k lines in loop to the server and it handles it perfectly if I dont write it to the file, only print the ouptut to the console And the full code with the changes your recommendations and with the log output commented
Then, the problem is with the output to the log file, can I make it asyncronous or save it in cache and write when it can? | [reply] [d/l] [select] |
by NetWallah (Canon) on Sep 28, 2018 at 16:40 UTC | |
I suspect that multiple threads appending to a file may be giving you trouble.
I suggest starting a separate thread to collect the output, and append it to a file in a single thread. Memory fault -- brain fried | [reply] |
Re: Client-Server app
by zentara (Archbishop) on Sep 27, 2018 at 18:36 UTC | |
In your code, try sprinkling warnings after socket operations, or print a debug message at critical points to see where your code fails when it crashes. Just as a longshot, that sometimes works, try putting $SIG{CHLD} = 'IGNORE' in your script. If you are going to stick with a select() while loop, it sometimes is useful to test for $socket->can_write at an appropriate place to give an indication that the socket is still alive. Here is a basic forking client that works really well for testing connections, the fork separates the send from the receive. It can get confusing, I hope the above helps you out. I'm not really a human, but I play one on earth. ..... an animated JAPH | [reply] [d/l] [select] |
Re: Client-Server app
by radu (Initiate) on Sep 28, 2018 at 19:07 UTC | |
Hello, I finally switched to POE, It works great for what I need and today I was working in a script with SSL support and works great. Here is the code
It's working like I want, obviusly still need a lot of work but hey, for now it's working pretty good Now the next thing I want is to make some authentication mechanism, any hint? What I was thinking is to save a plain text "database" or a postgresql table with a relation of ip address and token and match each IP address with the token The database connector and checks it's not the big deal here, what I need is some type of auth in the connect handle or something to not be very database intensive, for example I'm thinking to load the entire table to an array on load the listener and make it "static" and refresh the array every 30 seconds with a subroutine or something Really this is the "thing" I don't know how to do, what I'm trying to do is to make some bolean variable with the session-id and after first check insert it into the array and on each read/write from the client check it with the array I'm near to the answer or anyone have another mechanism to achieve this? Thanks for all, I really appreciate all the comments | [reply] [d/l] |
Re: Client-Server app
by bliako (Monsignor) on Sep 28, 2018 at 11:27 UTC | |
It works for me (and quite impressively too++). Maybe you are not running a proper OS? It is worth checking if number of open files or number of simultaneous connections at server is exceeded. Anyway, here is a client I whipped up to test your server:
Use it like so: client.pl 10 1 2 for sending between 1 and 2 commands per second over a total of 10 seconds to the server. If you want to test multiple simultaneous client connections do this: for i in `seq 1 2`; do (./client.pl 10 1 2; st=$?; if [ $st -ne 0 ]; then echo "FAILED with $st"; fi) & doneReplace seq 1 2 to seq 1 1000 to test 1000 clients simultaneously and see if your OS can handle that. bw, bliako | [reply] [d/l] [select] |
Re: Client-Server app
by radu (Initiate) on Oct 02, 2018 at 13:28 UTC | |
Ok, finally got a working code, I tested it with 1000 simultaneous clients running random commands and works pretty well. I'm using 3 shared hashes to mantain a shared relation between IP'ss and tokens for each one
I'm not 100% sure about the handling of the thread element and if all is ok, but is working. I don't know if it will be helpfuly for someone but as I got lot of help from perlmonks I want it to be here for everyone who wants to use it or use some parts of it What I need now is some tips or something that can be improved, but for now, It's working in replacement to my old PHP api and is about 400-500% faster. | [reply] [d/l] |
Re: Client-Server app
by bliako (Monsignor) on Sep 28, 2018 at 11:40 UTC | |
also, add the following in your server where you handle the QUIT case:
| [reply] [d/l] |