刚开始学java网络编程,遇到了个奇怪的bug
写了一个可以简单的互发消息的客户端和服务器端,先运行客户端再运行服务器端两个对话框都能打开但不能收发消息。先运行服务器端,服务器对话框能打开可是客户端对话框怎么都打不开,等我把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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
哦,谢了!
你把网络I/O放在UI线程里,把UI阻塞了。把socket相关的代码都放到一个线程中去运行,就行了。