- 論壇徽章:
- 0
|
最近想用Win32::GUI聊天客戶端軟件.
當(dāng)成功登錄服務(wù)器后,派生出一個線程,用來專門收數(shù)據(jù),主線程用來發(fā)送數(shù)據(jù).
以下是節(jié)選出的主要代碼,里面可能缺少了某些工具方法.
#!c:\perl\bin\perl.exe -w
use strict;
use Win32::GUI;
use threads;
use threads::shared;
use PerlChat::Chat;
use PerlChat::Config;
use PerlChat::Utils;
#初始化聊天類
my $config = getConfig("conf/config.conf");
my $chat = PerlChat::Chat->spawn($config->{ip},$config->{port});
my $mainWin = new Win32::GUI::Window(
-name => 'mainWin',
-text => '51GG',
-size => [ $s_Main->{w}, $s_Main->{h} ],
-onResize => \&mainWinResize,
-onMinimize => sub { 1 },
-onMaximize => sub { 1 },
-onTerminate => \&mainWinClose,
);
$mainWin->AddTextfield(
-name => 'Username',
-pos => [ $s_Login->{x} + 55, $s_Login->{y} + 20 ],
-size => [ 120, 20 ],
-prompt => [ "用戶名:", -45 ],
);
$mainWin->AddTextfield(
-name => 'Password',
-pos => [ $s_Login->{x} + 55, $s_Login->{y} + 40 ],
-size => [ 120, 20 ],
-password => 1,
-prompt => [ "密 碼:", -45 ],
);
$mainWin->AddButton(
-name => 'LoginServer',
-pos => [ $s_Login->{x} + 50, $s_Login->{y} + 70 ],
-title => '登錄',
-onClick => \&LoginServer,
);
$mainWin->AddButton(
-name => 'LogoutServer',
-pos => [ $s_Login->{x} + 100, $s_Login->{y} + 70 ],
-title => '注銷',
-disabled => 1,
-onClick => \&LogoutServer,
);
#主循環(huán)
$mainWin->Show();
Win32::GUI::Dialog();
sub LoginServer{
$chat = PerlChat::Chat->spawn($config->{ip},$config->{port}) unless ($chat->{dp});
my ($username,$password) = ($mainWin->{Username}->Text(),$mainWin->{Password}->Text());
my $loginStr = makeLoginStr($username,$password);
$mainWin->MessageBox('登錄信息發(fā)送失敗,請重新啟動本程序,點擊"確定"關(guān)閉本程序','錯誤',MB_OK | MB_ICONERROR) and return -1 unless ($chat->send_data($loginStr) == 0);
my $ret = $chat->recv_data(1);
$mainWin->MessageBox('系統(tǒng)繁忙,登錄失敗,請重新啟動本程序,點擊"確定"關(guān)閉本程序','錯誤',MB_OK | MB_ICONERROR) and return -1 unless ($ret == 1);
my $threadRecvMsg = threads->create(sub {$chat->recv_data($mainWin);});
$threadRecvMsg->detach();
}
sub LogoutServer
{
my $logoutStr = "~2~" . $chat->{'uin'} . "~100~200~1~0~0";
$logoutStr = ( length($logoutStr) - 1 ) . $logoutStr;
$chat->{'dp'}
->send_data( $chat->{'sock'},$logoutStr);
$chat->{'dp'}->close_socket( $chat->{'sock'} );
}
__END__
|
但是遇到一個問題是,當(dāng)派生出一個新線程后,就只能收數(shù)據(jù)了,主線程不能發(fā)數(shù)據(jù)了.因為收數(shù)據(jù)和發(fā)數(shù)據(jù)需要共用一個socket,我把這個socket存在一個聊天對象中.
這時候就有個在不同線程間共享socket的問題.
我用threads::shared模塊的share方法來共享數(shù)據(jù),
在程序的最開始想直接共享$chat這個對象.但是同樣只能收不能發(fā).
我嘗試在login方法中加入只對$chat->{'socket'}共享,但是Perl提示:Cannot share globs yet.
不知道我有沒有描述清楚,我估計原因可能是socket沒有共享.所以導(dǎo)致只能收不能發(fā).
請問這種情況應(yīng)該怎樣解決.謝謝.
如果我哪個地方?jīng)]有描述清楚我會補上. |
|