刚开始学java网络编程,遇到了个奇怪的bug? 400 报错 写了一个可以简单的互发消息的客户端和服务器端,先运行客户端再运行服务器端两个对话框都能打开但不能收发消息。先运行服务器端,服务器对话框能打开可是客户端对话框怎么都打不开,等我把eclipse关掉,客户端的对话框会跳出来再关掉。
代码如下,求大神们帮忙看看哪里出了问题:(两段代码是在两个project里)
1.服务器代码
public class MyServer extends JFrame {
private JTextArea jta = new JTextArea();
private JScrollPane jsp = new JScrollPane(jta);
private JTextField jtf = new JTextField(20);
private JPanel panel = new JPanel();
private JButton btn = new JButton("发送");
private PrintWriter pw = null;
public MyServer() {
try {
ServerSocket ss = new ServerSocket(8888);
Socket s = ss.accept();
InputStreamReader isr = new InputStreamReader(s.getInputStream());
BufferedReader br = new BufferedReader(isr);
pw=new PrintWriter(s.getOutputStream(),true);
while (true) {
String msgClient = br.readLine();
jta.append("来自客户端: \n");
jta.append(msgClient + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msgServer = jtf.getText();
if (msgServer != null) {
jta.append("来自服务器: \n");
jta.append(msgServer + "\n");
pw.print(msgServer);
jtf.setText("");
}
}
});
panel.add(jtf);
panel.add(btn);
jsp.setBorder(new LineBorder(Color.black));
add(jsp, BorderLayout.CENTER);
add(panel, BorderLayout.SOUTH);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("服务器端");
this.setSize(400, 300);
this.setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MyServer myClient = new MyServer();
}
}
2.客户端
public class MyClient extends JFrame{
private JTextArea jta=new JTextArea();
private JScrollPane jsp=new JScrollPane(jta);
private JTextField jtf=new JTextField(20);
private JPanel panel=new JPanel();
private JButton btn=new JButton("发送");
private PrintWriter pw=null;
public MyClient(){
try {
Socket s = new Socket("127.0.0.1",8888);
InputStreamReader isr=new InputStreamReader(s.getInputStream());
BufferedReader br=new BufferedReader(isr);
pw=new PrintWriter(s.getOutputStream());
while(true){
String msgServer=br.readLine();
jta.append("来自服务器:\n");
jta.append(msgServer+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String msgClient=jtf.getText();
jta.append("来自客户端:\n");
jta.append(msgClient+"\n");
pw.print(msgClient);
jtf.setText("hello");
}
});
panel.add(jtf);
panel.add(btn);
jsp.setBorder(new LineBorder(Color.black));
add(jsp,BorderLayout.CENTER);
add(panel,BorderLayout.SOUTH);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("客户端");
this.setSize(400,300);
this.setVisible(true);
}
public static void main(String[] args) {
MyClient myClient=new MyClient();
}
}
你把网络I/O放在UI线程里,把UI阻塞了。把socket相关的代码都放到一个线程中去运行,就行了。
######哦,谢了!版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。