简体   繁体   English

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

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

I have a big issue with my java client. 我的Java客户端有个大问题。

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

$n is the socket $ n是套接字

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

When a client send a message to the server 客户端向服务器发送消息时

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

In 'talk' the server send the client message back to the client 在“对话”中,服务器将客户端消息发送回客户端

Client: Java, in a Thread I send a byte array -> 客户端: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);
   }
  }
 }

If I try to send 如果我尝试发送

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

I receive nothing!!! 我什么也没收到!

Did i missed something, I assume that if I send 我错过了什么吗,我假设如果我发送

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

I should receive 50,4 :) 我应该收到50,4 :)

Thanks, 谢谢,

Your Perl code is doing <$n> so it's fetching data line-by-line. 您的Perl代码正在执行<$n>因此它正在逐行获取数据。 since 10 is the line-feed character, receiving a {10,4} sequence means it gets an empty line (which it prints back) and then a character 4. Even if it receives that (some debug messages in the Perl code would help), the print back to the socket may not complete if the socket is block-buffered (likely the default) without flushing the socket filehandle. 因为10是换行字符,所以接收到{10,4}序列意味着它得到一个空行(它将打印回去),然后是一个字符4。即使接收到该行(Perl代码中的某些调试消息也会有所帮助) ),如果套接字在没有刷新套接字文件句柄的情况下被块缓冲(可能是默认值),则无法完成返回套接字的打印。

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

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

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