[英]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.