本帖最后由 Simple_love 于 2013-10-27 22:56 编辑
在网络编程中使用readUTF()等操作输入输出流时容易产生阻塞。比如写一个聊天的程序,只能一边说一句,另一边接收完程序才能往下执行。这要如何解决?有没有聊天程序两边可以任意输入的源代码给个?
public class chatClient extends Frame {
/*** @param args*/
TextField tfTxT=new TextField();
TextArea taContent=new TextArea();
Socket s=null;DataOutputStream dos=null;
DataInputStream dis=null;
private boolean bConnected =false;
public static void main(String[] args) {
new chatClient().lunachFrame();
}
private class RecvThread() implements Runnable{
public void run() {
try{
while(bConnected){
String str=dis.read()UTF();
taContent.setText(taContent.getText()+str+'\n');
}
}catch(IOException e){
e.printStackTrace();
}
}
}
public void lunachFrame(){
this.setLocation(400, 300);
this.setSize(300,300);
//this.setLayout(new FlowLayout());
this.add(tfTxT,"South");
this.add(taContent,"North");
pack();
tfTxT.addActionListener(new TFListener());
this.addWindowListener(new WindowClose());
this.setVisible(true);connect()();
new Thread()(new RecvThread()).start();
}
public void connect()(){
try {s= new Socket("127.0.0.1",8888);
dos =new DataOutputStream(s.getOutputStream());
dis =new DataInputStream(s.getInputStream());
System.out.println("connect()ed!");
bConnected=true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect(){
try {
dos.close();s.close();
} catch (Exception e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
class WindowClose extends WindowAdapter{
@Override
public void windowClosing(WindowEvent e) {
// TODO 自动生成方法存根
System.exit(0);disconnect();
}
}
private class TFListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String str=tfTxT.getText().trim();
//trim去掉两边空格//
taContent.setText(str);tfTxT.setText("");
try {
dos.writeUTF(str);
dos.flush();
//dos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
|