我的 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/