📄 example1104_udpb.java
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
public class Example1104_UDPB extends JFrame implements Runnable,ActionListener
{
JTextField hostcom;
JTextArea listcom;
JTextField infocom;
public Example1104_UDPB()
{
super("Example1104_UDPB");
setBounds(getToolkit().getScreenSize().width/2,0,getToolkit().getScreenSize().width/2,600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container con=getContentPane();
Box box1=Box.createHorizontalBox();
hostcom=new JTextField();
box1.add(new JLabel("目的主机"));
box1.add(hostcom);
listcom=new JTextArea();
listcom.setEditable(false);
Box box2=Box.createHorizontalBox();
infocom=new JTextField();
infocom.addActionListener(this);
box2.add(new JLabel("发送消息"));
box2.add(infocom);
con.add(box1,"North");
con.add(new JScrollPane(listcom),"Center");
con.add(box2,"South");
Thread thread=new Thread(this);
thread.start();
setVisible(true);
}
public void actionPerformed(ActionEvent evt)
{
try
{
InetAddress host=InetAddress.getByName(hostcom.getText());
byte[] buff=infocom.getText().getBytes();
infocom.setText(null);
infocom.requestFocus();
listcom.append(InetAddress.getLocalHost()+":\n"+new String(buff)+"\n\n");
DatagramPacket packet=new DatagramPacket(buff,buff.length,host,6666);
DatagramSocket socket=new DatagramSocket();
socket.send(packet);
socket.close();
}
catch (Exception e)
{
listcom.append("Exception in sending DatagramPacket!\n\n");
}
}
public void run()
{
DatagramPacket packet=null;
DatagramSocket socket=null;
try
{
byte[] buff=new byte[8192];
packet=new DatagramPacket(buff,buff.length);
socket=new DatagramSocket(5555);
}
catch (Exception e)
{
listcom.append("Exception in creating DatagramPacket and DatagramSocket!\n\n");
}
while (true)
{
try
{
socket.receive(packet);
InetAddress host=packet.getAddress();
String info=new String(packet.getData(),0,packet.getLength());
listcom.append(host+":\n"+info+"\n\n");
}
catch (Exception e)
{
listcom.append("Exception in receiving DatagramPacket!\n\n");
}
}
}
public static void main(String[] args)
{
new Example1104_UDPB();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -