- 论坛徽章:
- 0
|
各位好.
我写了一个小socket的server端.工作机制很简单,就是遍历文件,然后如果标志文件存在就生成一个session_id.这个session_id是system 调用系统命令.生成一个8位的随即字符串.
在socket部分,将变量$session_id 用send函数传送给client端.
可是client端无法获得该值.
我调试和判断后认为,应该是在$session_id 在语句体中的变量类型有问题,应该加上my. 但是,还是不行.
如果将send 的内容改为:
print CLIENT "hello world!\n";
send(CLIENT,$flag,0);
或者
print SESSION (my $s = localtime); #直接调一个系统函数;
client端都是可以接收到值的.
因为本人是perl初学者,对于perl细节问题理解的不是很透彻.尤其是对于局部变量这块.
麻烦各位高手多多指教!代码如下:
============================
#!/usr/bin/perl
#LastUpdated:2006-06-21
#Server end
##use strict;
use warnings;
use IO::Handle;
use Socket;
#File define;
$prefix="/opt/modules/kdn/etc/";
$pds_filename="pds_channel_list.txt";
$server_config_file= $prefix.$pds_filename;
$flag_file=".ht_file";
$changename=".ht_file.old";
my $syn_start=0;
#Socket define;
$port=6880;
$address=sockaddr_in($port,INADDR_ANY);
socket(SERVER,AF_INET,SOCK_STREAM,getprotobyname('tcp'));
bind(SERVER,$address);
listen(SERVER,10);
#Become a Daemon
my $pid = fork();
print $pid,"\n";
if($pid) {
#end parent process
print "#parent process\n";
exit(0);
}else {
print "#child process";
}
# set new process group
setpgrp;
#Loop ;
while(1) {
sleep(30);
#Open file and read erveryline;
open( OPF, $server_config_file)||die "Cannt open File: $server_config_file\n";
@content = <OPF>;
close (OPF);
foreach $line (@content){
next if ($line =~ /^\s+/ || $line =~ /^#*$/);
@str = (split( /,/, $line));
$codename = $str[0];
$filepath = $str[1];
#print ("$codename\n$filepath\n$server_config_file\n");
$flag_all = $filepath.$flag_file;
if (-e $flag_all){
$syn_start = 1;
my $flag = $syn_start;
if ($syn_start == 1){
print ("syn_start flag: $syn_start\n");
$sessionid = system 'date +%N | md5sum | head -c 8';
#print ("$sessionid\n");
## example:rename(/opt/data/.ht_file,/opt/data/.ht_file.old);
#rename("$flag_all","$filepath/$changename");
}
}else {
warn "$flag_all doesnt exist\n";
}
}
open ("TEST",">>/tmp/test.log");
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
$year+=1900;$mon++;
print TEST ("INFO:$year-$mon-$mday $hour:$min:$sec.running is OK!\n");
close (TEST);
next unless (accept(CLIENT,SERVER));
CLIENT->autoflush(1);
print CLIENT "$flag\n";
send(CLIENT,$flag,0);
close CLIENT;}
close SERVER;
=====================================
#!/usr/bin/perl -w
#LastUpdated:2006-06-16
#client end
##use strict;
use warnings;
use IO::Handle;
use Socket;
$port=6880;
$host='localhost';
$packhost=inet_aton($host);
$address=sockaddr_in($port,$packhost);
while(1) {
sleep(10);
socket(CLIENT,AF_INET,SOCK_STREAM,6);
connect(CLIENT,$address);
CLIENT->autoflush(1);
recv(CLIENT,$sessionid,length($sessionid),0);
$sessionid=<CLIENT>;
print "RECV:$sessionid\n";
close CLIENT;
} |
|