问题描述
我有一个Java应用程序,即Voip.我正在使用一个套接字通过线程同时发送和接收信息.代码如下所示.
I have a Java application which is Voip. I am using the one socket to send and receive information at the same time via threads. Code is shown below ..
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();
我发现的问题是,当我写到输出流时,它在第一次写时阻塞.我发送的字节不多.贝娄是我的写代码.
The problem that I'm finding is that when I write to the outputstream, it blocks on the first write. I'm sending not many bytes. Bellow is my write code.
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){}
}
}
读取声音代码的另一个线程是...
The other thread that reads the sound code is ...
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){}
}
}
由于我只是想使其正常工作,因此我已经注释了大部分实际代码.我的写函数在第一次写时无限期地阻塞.可能这可能是我的线程有问题吗?我唯一的想法是输出流和输入流共享我的套接字对象,这可能会导致死锁或其他问题.请让我知道最新情况.
I've commented a good portion of the actual code since I'm just trying to get it to work. My write function blocks indefinitely on the first write. Is it possible this could be a problem with my threads? My only thought is that the output and input streams are sharing my socket object which may cause a deadlock or something. Please let me know whats up.
推荐答案
是的,您可以同时写入套接字的输入和输出流.
Yes you can write to a sockets input and output stream at the same time.
来自 do-java-sockets-support-full-duplex
这篇关于您可以同时写入套接字的输入和输出流吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!