【发布时间】:2019-07-01 05:26:51
【问题描述】:
我现在正在为简单的通信进行套接字编程。
我注意到服务器不是我创建的,它工作正常(给定实验客户端)
在我的代码中,recv 工作正常,但 send 不工作。我的代码有什么问题吗?
my $socket = new IO::Socket::INET (
#PeerHost => '127.0.0.1',
PeerHost => '192.168.0.100',
PeerPort => '8472',
Proto => 'tcp',
);
die "cannot connect to the server $!\n" unless $socket;
print "connected to the server\n";
while (1) {
my $response = "";
$socket->recv($response, 1024);
if ($response) {
my @test = split(//,$response);
my ($length,$data) = unpack("N A*",$response);
%json = json_decode($data,$length);
switch ($json{'type'}) {
case 1 { print "Game Start\n";}
#case 2 { my $tmp = &my_turn(%json);} #my_turn func is return "{'type': 0, 'point': [5, 4]}", but fail!
#case 2 { $socket->send("{'type': 0, 'point': [5, 4]}");} # fail!
case 2 { print $socket "{'type': 0, 'point': [5, 4]}"; print "ok\n";} # print is executed. However, the server does not receive packets
#case 2 { $socket->send("{'type': 0, 'point': [5, 4]}");} #fail...
case 3 { print "ACCEPT\n";}
case 5 { print "NOPOINT\n";}
case 6 { print "GAMEOVER\n";}
case 7 { print "ERROR\n";}
else {print "ERROR type : $json{'type'}\n"}
}
}
}
服务器工作正常。我检查了服务器提供的示例源代码(python 代码)。我错过了什么?
【问题讨论】:
-
请添加
use strict;和use warnings;做你的代码。然后修复报告的错误并更新您的问题。 -
您的代码存在几个问题:(a) 您没有检查
recv()确实返回了多少字节。它可能比您要求的要少,(b) JSON 解码返回 refs,即它应该是my $json = json_decode($response);和switch($json->{type}) { -
您还可以在
SOCK_STREAM套接字上使用recv()。 -
您发送的消息不应该像您收到的消息一样使用长度前缀吗?