繁体   English   中英

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

[英]Send byte array through socket between perl and Java

我的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代码中的某些调试消息也会有所帮助) ),如果套接字在没有刷新套接字文件句柄的情况下被块缓冲(可能是默认值),则无法完成返回套接字的打印。

您可能想显式使用read (而不是隐式的readline ,顾名思义, readline读到行尾或EOF)从套接字读取。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM