我正在尝试使用套接字将数据从我的 Android 手机发送到我的家庭服务器。我的服务器运行 Linux,所以我使用 Perl 为我的服务器编写脚本。连接工作正常,我可以将数据发送到我在手机上运行的客户端。
问题是,当我向服务器发送一些东西(第一次尝试是一个简单的字符串)时,我在服务器端没有收到任何东西。如果我使用 telnet 向服务器发送字符串,一切正常。
我在这里坐了一段时间,我查看是否有与我类似的问题,但找不到任何讨论 Android 到 Perl 脚本的问题。这是我的 Android 应用程序代码:
try {
Socket socket = new Socket("192.168.178.22", 22222);
Statusinformation("connection with server succeed");
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Statusinformation(input.readLine());
OutputStream outstream =socket.getOutputStream();
PrintWriter out = new PrintWriter(outstream);
out.println("This is a test message from client on phone!\n");
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
Statusinformation("connection unsucsessfull");
e.printStackTrace();
}
在我的手机上,如果我执行上面的代码,我会收到这个:
连接服务器成功!
在服务器端,我使用这段代码从套接字客户端接收字符串:
use IO::Socket;
my $server = IO::Socket::INET -> new(
Proto => 'tcp',
LocalPort => 22222,
Listen => SOMAXCONN,
);
print "Server started..\n";
while (1) {
next unless my $conect = $server -> accept();
my $childconection = fork;
if ($childconection == 0) {
handle_connection($conect);
}
}
sub handle_connection
{
my $sock = shift;
my $client_message="";
my $client_addr = $sock -> peerhost;
print "connection: $client_addr connected\n";
print $sock "hi $client_addr, you are connected!\n";
while (1) {
open (Tempfile, '>>tempfile.txt');
while ($client_message = <$sock>) {
print Tempfile $client_message;
print $client_message;
}
close (Tempfile);
}
close($sock);
exit(0);
}
最佳答案
好吧,现在我有点惭愧。 我通过添加解决了这个问题: out.flush(); flush() 方法确保所有未决数据都发送到目标并刷新目标。
关于android - 运行perl skript的服务器和android之间的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17124257/