我使用java制作了一个语音呼叫应用程序。该帧由两个按钮组成,一个是呼叫,另一个是切断呼叫。我的问题是每当我按下呼叫按钮时线程开始运行并且数据(语音)连续传输,但其他操作(如剪切按钮或帧关闭按钮)根本不响应。就像框架挂起一样。有人可以帮我解决这个问题吗?
编辑:这是我的客户端代码。没有为服务器制作任何帧。它只是在另一台机器上运行。
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;
import javax.sound.sampled.*;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Program extends JFrame implements ActionListener
{
JButton jbtOpen, c;
JFrame f1=new JFrame();
JPanel PPanel1;
JLabel limg=new JLabel();
public final static String SERVER = JOptionPane.showInputDialog("Please enter server IP");
public Program()
{
PPanel1 = new JPanel(null);
PPanel1.setPreferredSize(new Dimension(1366,786));
Container con=getContentPane();
ImageIcon image1 = new ImageIcon("voicecall.jpg");
ImageIcon image2 = new ImageIcon("voicecall1.jpg");
ImageIcon image3 = new ImageIcon("call.jpg");
jbtOpen=new JButton("Call");
c=new JButton("Cut");
limg.setIcon(image1);
jbtOpen.setIcon(image2);
c.setIcon(image3);
limg.setBounds(0,0,1500,700);
jbtOpen.setBounds(50,50,100,100);
c.setBounds(200,50,100,100);
PPanel1.add(limg);
PPanel1.add(jbtOpen);
PPanel1.add(c);
setSize(400, 400);
setVisible(true);
setTitle("Voice Calling");
con.add(PPanel1,BorderLayout.WEST);
jbtOpen.addActionListener(this);
c.addActionListener(this);
f1.addWindowListener(new W1());
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == jbtOpen)
{
try {
open();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(e.getSource() == c){
System.exit(0);
}
}
}
public void open() throws Exception
{
AudioFormat af = new AudioFormat(8000.0f,8,1,true,false);
DataLine.Info info = new DataLine.Info(TargetDataLine.class, af);
TargetDataLine microphone = (TargetDataLine)AudioSystem.getLine(info);
microphone.open(af);
Socket conn = new Socket(SERVER,3000);
microphone.start();
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
int bytesRead = 0;
byte[] soundData = new byte[1];
Thread inThread = new Thread(new SoundReceiver(conn));
inThread.start();
while(bytesRead != -1)
{
bytesRead = microphone.read(soundData, 0, soundData.length);
if(bytesRead >= 0)
{
dos.write(soundData, 0, bytesRead);
}
}
System.out.println("IT IS DONE.");
}
public static void main(String args[])
{
Program b=new Program();
}
private class W1 extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
}
答案 0 :(得分:0)
此代码存在多个问题。 actionPerformed
方法永远不会到达System.exit()因为你有这个代码块:
if(e.getSource() == c){
System.exit(0);
}
内部 if(e.getSource() == jbtOpen)
代码块。你至少需要一个其他人。
System.exit()不是清理正在运行的线程的好方法。至少应该使用中断()或其他东西,你应该更优雅地关闭它。