我有一個Java應用程序是Voip。我正在使用一個套接字通過線程同時發送和接收信息。代碼如下所示。您可以同時寫入套接字輸入和輸出流嗎?
Socket clientSocket = sockList.accept();
OutputStream outSock = clientSocket.getOutputStream();
InputStream inSock = clientSocket.getInputStream();
new Thread(new Capture(outSock)).start();
new Thread(new PlayAudio(inSock)).start();
outSock.close();
clientSocket.close();
我發現的問題是,當我寫入輸出流時,它會在第一次寫入時阻塞。我發送的字節數不多。貝婁是我寫的代碼。
private class Capture implements Runnable{
private OutputStream out;
public Capture(OutputStream out){
this.out = out;
}
@Override
public void run() {
try{
int numBytesRead;
TargetDataLine outLine = getMic();
outLine.open();
outLine.start();
byte[] data = new byte[outLine.getBufferSize()/5];
byte[] test = {0x1,0x1,0x1};
while(true) {
//numBytesRead = outLine.read(data, 0, data.length);
//System.out.println(numBytesRead);
out.write(test, 0, test.length);
out.flush();
/*if(numBytesRead > 0){
out.write(data, 0, data.length);
System.out.println("C");
}*/
}
}catch(Exception ex){}
}
}
另一個線程讀取的音頻碼是...
private class PlayAudio implements Runnable{
private InputStream in;
public PlayAudio(InputStream in){
this.in = in;
}
@Override
public void run() {
int write;
try{
SourceDataLine inLine = getSpeaker();
inLine.open();
inLine.start();
byte[] data = new byte[inLine.getBufferSize()];
byte[] test = new byte[3];
while(true){
System.out.println(1);
//write = in.read(data, 0, data.length);
in.read(test, 0 , test.length);
System.out.println(2);
/*if(write > 0){
inLine.write(data, 0, write);
System.out.println(3);
System.out.println(write);
}*/
}
} catch(Exception ex){}
}
}
我評論的實際代碼的很大一部分,因爲我只是想獲得它的工作。我的寫入功能在第一次寫入時無限期地阻塞。這可能是我的線程有問題嗎?我唯一的想法是,輸出和輸入流共享我的套接字對象,這可能會導致死鎖或什麼。請讓我知道最新情況。
我認爲,由於進出(兩個獨立的流)是獨立的對象,同時對它們進行操作應該沒有關係。所以你說我應該仍然擔心同步,不管? –