通过 TCP 套接字将音频写入服务器
我正在尝试通过TCP套接字将实时麦克风录音传输到服务器,并将输入流写入文件。连接已建立,但一段时间后,我在客户端收到连接拒绝错误。
服务器代码:
public class auServer extends Thread{
private static ServerSocket serverSocket;
private static int port = 3333;
public void run()
{
System.out.println("init success");
while(true)
{
try
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
Socket clientSoc = serverSocket.accept();
System.out.println("Waiting for client on port " +serverSocket.getLocalPort() + "...");
System.out.println("Just connected to " + clientSoc.getRemoteSocketAddress());
InputStream in = clientSoc.getInputStream();
while(in!=null)
{
writeToFile(in);
}
System.out.println("socket");
clientSoc.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
System.out.println("some io");
break;
} catch (Exception e) {
System.out.println("some e");
e.printStackTrace();
}
}
}
private void writeToFile(InputStream in) throws IOException {
// Write the output audio in byte
String filePath = "8k16bitMono1.wav";
short sData[] = new short[1024];
byte[] bData = IOUtils.toByteArray(in);
FileOutputStream os = null;
try {
os = new FileOutputStream(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("Short wirting to file" + sData.toString());
try {
os.write(bData, 0, 2048);
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
Thread serverThread = new auServer();
serverThread.run();
System.out.println("runing");
}catch(IOException e){
e.printStackTrace();
}
}
}
和客户端 :
private void streamData(byte[] bData) throws UnknownHostException, IOException, InterruptedException { //bData is byte array to transmit
Thread.sleep(500);
Socket client = new Socket("10.221.40.41",3333);
OutputStream outToServer = client.getOutputStream();
outToServer.write(bData);
if(!isRecording)
client.close();
}
可能是什么问题?提前致谢。