请将下面的java程序代码给加详细的注释(部分已给出),谢谢了,回答满意再追加20分publicclassChatUDPJFrameextendsJFrameimplementsActionListener{privateStringname;//网名privat...
请将下面的java程序代码给加详细的注释(部分已给出),谢谢了,回答满意再追加20分
public class ChatUDPJFrame extends JFrame implements ActionListener
{
private String name; //网名
private InetAddress destip; //目标主机名或IP地址
private int destport; //目标主机的端口号
private JTextArea text_receiver; //显示对话内容的文本区
private JTextField text_sender; //输入发送内容的文本行
public ChatUDPJFrame(String name, String host, int destport, int receiveport) throws Exception
{
super("聊天室 "+name+" "+InetAddress.getLocalHost()+" : "+receiveport);
this.setBounds(320,240,400,240);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.text_receiver = new JTextArea();
this.text_receiver.setEditable(false);
this.getContentPane().add(new JScrollPane(this.text_receiver));
JPanel panel = new JPanel();
this.getContentPane().add(panel,"South");
this.text_sender = new JTextField(20);
panel.add(this.text_sender);
JButton button_send = new JButton("发送");
panel.add(button_send);
button_send.addActionListener(this);
this.setVisible(true);
this.name = name;
this.destip = InetAddress.getByName(host);
this.destport= destport;
byte data[] = new byte[512]; //以下接收数据报包并显示
DatagramPacket pack=new DatagramPacket(data,data.length); //创建待接收数据报包
DatagramSocket socket=new DatagramSocket(receiveport); //创建待接收Socket
while (socket!=null)
{
socket.receive(pack); //接收数据报包
int length=pack.getLength(); //获得包长度
String message=new String(pack.getData(),0,length);//获得包中字节数据并转成字符串
text_receiver.append(message+"\r\n");
}
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand()=="发送")
{
byte buffer[]=(name+" 说:"+text_sender.getText()).getBytes(); //将字符串转换成字节
try
{
DatagramPacket pack=new DatagramPacket(buffer, buffer.length, destip, destport);
new DatagramSocket().send(pack); //绑定一个可用端口发送数据报
}
catch(Exception ex)
{
ex.printStackTrace();
}
text_receiver.append("我说:"+text_sender.getText()+"\n");
text_sender.setText("");
}
}
public static void main(String args[]) throws Exception
{
new ChatUDPJFrame("玉公主", "127.0.0.1", 3001, 3002);
}
}
展开