0
我正在編碼使用java的套接字進行語音聊天,兩個客戶端通話成功,但延遲1-2s。我不知道爲什麼。導致網速或我的代碼使用java和套接字的vocie聊天,當連接局域網時延遲
線球員
public class player extends Thread{
public DataInputStream din = null;
public SourceDataLine audio_out;
byte byte_buff[] = new byte[256];
@Override
public void run(){
try {
while(din.read(byte_buff)!= -1){
audio_out.write(byte_buff, 0, byte_buff.length);
}
audio_out.drain();
audio_out.close();
} catch (IOException ex) {
Logger.getLogger(player.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
din.close();
} catch (IOException ex) {
Logger.getLogger(player.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
線程記錄
public class recorder extends Thread{
public DataOutputStream dout = null;
public TargetDataLine audio_in = null;
byte byte_buff[] = new byte[256];
@Override
public void run(){
try {
while(true){
int data = audio_in.read(byte_buff, 0, byte_buff.length);
//audio_out.write(byte_buff, 0, byte_buff.length);
System.out.println("sending");
dout.write(byte_buff);
dout.flush();
}
} catch (IOException ex) {
Logger.getLogger(recorder.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
dout.close();
} catch (IOException ex) {
Logger.getLogger(recorder.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
線遞送
public class transfer extends Thread{
DataInputStream din;
DataOutputStream dout;
byte byte_buff[] = new byte[256];
@Override
public void run(){
try {
while(din.read(byte_buff)!= -1){
dout.write(byte_buff, 0, byte_buff.length);
System.out.println("tranferring");
}
} catch (IOException ex) {
System.out.println("voice disconnect");
} finally {
try {
din.close();
} catch (IOException ex) {
Logger.getLogger(transfer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
運行沒有問題,但推遲約1-2S,兩個客戶端在局域網上連接。 請幫我
對於初學者來說,TCP可能會產生大量抖動,這是從未用於語音聊天的主要原因之一。您應該使用UDP。 – chrylis
謝謝,我照你說的做了,成功感謝很多:)) – duongtan