下面的程序存在问题 每次运行的时候都会抛出异常而且点击按钮之后也会有异常产生,我是在本机上测试的,本人刚接触java不久希望大虾们腾出点时间帮帮忙改一下 初步判断异常的原因事DatagramSocket定义的时候,还有new Thread也存在问题 谢谢了
import java.awt.*;
import java.awt.event.*;
import java.net.*;
public class Chat_Frame extends JFrame {
JPanel contentPane;
JTextArea jTextArea1 = new JTextArea();
JTextArea jTextArea2 = new JTextArea();
JTextField jTextField1 = new JTextField();
JLabel jLabel1 = new JLabel();
JButton jButton1 = new JButton();
JButton jButton2 = new JButton();
static DatagramSocket ds = null;
static {
try {
ds = new DatagramSocket(3000);
} catch (Exception e) {
}
}
public Chat_Frame() {
try { setDefaultCloseOperation(EXIT_ON_CLOSE);
jbInit();
} catch (Exception exception) {}
}
private void jbInit() throws Exception {
contentPane = (JPanel) getContentPane();
contentPane.setLayout(null);
setSize(new Dimension(416, 520));
setTitle("Frame Title");
scrollPane1.setBounds(new Rectangle(6, 19, 401, 219));
scrollPane2.setBounds(new Rectangle(6, 246, 400, 173));
jTextField1.setBounds(new Rectangle(72, 436, 143, 30));
jLabel1.setText("对方IP");
jLabel1.setBounds(new Rectangle(6, 439, 60, 26));
jButton1.setBounds(new Rectangle(244, 436, 74, 29));
jButton1.setText("发送");
jButton1.addActionListener(new Chat_Frame_jButton1_actionAdapter(this));
jButton2.setBounds(new Rectangle(338, 436, 67, 28));
jButton2.setText("退出");
jButton2.addActionListener(new Chat_Frame_jButton2_actionAdapter(this));
jTextArea2.addKeyListener(new Chat_Frame_jTextArea2_keyAdapter(this));
contentPane.add(scrollPane1);
scrollPane1.add(jTextArea1);
contentPane.add(scrollPane2);
contentPane.add(jTextField1);
contentPane.add(jLabel1);
contentPane.add(jButton1);
contentPane.add(jButton2);
scrollPane2.add(jTextArea2);
new Thread(new Runnable() {
public void run() {
byte buf[] = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024); while (true) {
try {ds.receive(dp);
jTextArea1.append(new String(buf, 0, dp.getLength()) +"\n");
} catch (Exception e) {}}}}}).start();
}
public void jButton1_actionPerformed(ActionEvent e) {
byte buf[];
buf = jTextArea2.getText().getBytes();
try {
DatagramPacket dp = new DatagramPacket(buf, buf.length,InetAddress.getByName(jTextField1.getText()), 3000);
ds.send(dp);
} catch (Exception ex) {}
}
public void jButton2_actionPerformed(ActionEvent e) {
ds.close();
dispose();
System.exit(0);
}
}
java通过UDP实现通信问题
答案:2 悬赏:0 手机版
解决时间 2021-02-07 06:54
- 提问者网友:最爱你的唇
- 2021-02-06 20:59
最佳答案
- 五星知识达人网友:动情书生
- 2021-02-06 21:36
可能是端口问题,你重启一下java运行环境应该就可以!
全部回答
- 1楼网友:低音帝王
- 2021-02-06 22:09
把异常发出来看下!
做JAVA要学会看错误
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯