java - Perl 和 Java 之间通过套接字发送字节数组

标签 java arrays perl client

我的 java 客户端有一个大问题。

服务器:perl,带有 IO::Socket;

$n 是套接字

    sub listen{    
 while(1){
  my $n = $_[0]->accept();
  my $thread;
  my $thread2;
  $thread = threads->create('talk', $n);
  $thread2 = threads->create('recu', $n);
 }

当客户端向服务器发送消息时

    sub talk{
 my $n = $_[0];
 while(<$n>){
  print $n $_;
 }

在“谈话”中,服务器将客户端消息发送回客户端

客户端:Java,在线程中 我发送一个字节数组 ->

static DataOutputStream os;

...

     public static void handleMsg(byte [] b){
  try {
   os.write(b);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

->

<pre><code>
    byte[] buff = new byte[]{10,4};
ThreadListen.handleMsg(buff);
</code></pre>
I receive in the run() method only the first byte in the array (10)
<pre><code>
    public void run(){
  DataInputStream in = null;
  try{
   in = new DataInputStream(s.getInputStream());
  } catch (IOException e) {
   System.out.println("in or out failed");
   System.exit(-1);
  }

  while(true){
   try{
    byte[] buff = new byte[6];
    int b = in.read(buff, 0, buff.length);
   }catch (IOException e) {
    System.out.println("Read failed");
    System.exit(-1);
   }
  }
 }

如果我尝试发送

byte[] buff = new byte[]{50,4};
ThreadListen.handleMsg(buff);

我什么也没收到!!!

我是否错过了什么,我假设如果我发送

byte[] buff = new byte[]{50,4};

我应该收到 50,4 :)

谢谢

最佳答案

你的 Perl 代码正在做 <$n>所以它是逐行获取数据的。由于 10 是换行符,因此接收 {10,4}序列意味着它得到一个空行(它打印回来),然后是一个字符 4。即使它接收到该空行(Perl 代码中的一些调试消息会有所帮助),如果套接字被阻止,则打印回套接字可能无法完成-buffered(可能是默认值)而不刷新套接字文件句柄。

关于java - Perl 和 Java 之间通过套接字发送字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4366136/

相关文章:

perl - 我们如何在 Perl 中为 "use"命令使用变量?

java - 未找到 HTTP 请求与 URI 的映射

java - 具有多个拆分参数的 Guava 拆分器

java - 向 JPanel 添加图形

PHP - 对象数组中丢失引用?

perl - map perl 从值循环

java - 在 EclipseLink 2.7 中不选择更新

php - mysql在PHP中选择单列作为单维数组

php - 获取将 PHP 数组一分为二的所有可能组合

regex - 使用 perl 而不是 grep