?? receive.java
字號:
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class Receive extends Frame implements Runnable,ActionListener
{
int port;
InetAddress group=null;
MulticastSocket socket=null;
Button 開始接收,停止接收;
TextArea 顯示正在接收內容,顯示已接收的內容;
Thread thread;
boolean 停止=false;
public Receive()
{
super("定時接收信息");
thread=new Thread(this);
開始接收=new Button("開始接收");
停止接收=new Button("停止接收");
停止接收.addActionListener(this);
開始接收.addActionListener(this);
顯示正在接收內容=new TextArea(10,10);
顯示正在接收內容.setForeground(Color.blue);
顯示已接收的內容=new TextArea(10,10);
Panel north=new Panel();
north.add(開始接收);
north.add(停止接收);
add(north,BorderLayout.NORTH);
Panel center=new Panel();
center.setLayout(new GridLayout(1,2));
center.add(顯示正在接收內容);
center.add(顯示已接收的內容);
add(center,BorderLayout.CENTER);
validate();
port=5000;
try{
group=InetAddress.getByName("239.255.0.0");
socket=new MulticastSocket(port);
socket.joinGroup(group);
}
catch(Exception e)
{
}
setBounds(100,50,360,380);
setVisible(true);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==開始接收)
{
開始接收.setBackground(Color.blue);
停止接收.setBackground(Color.gray);
if(!(thread.isAlive()))
{
thread=new Thread(this);
}
try
{
thread.start();
停止=false;
}
catch(Exception ee)
{
}
}
if(e.getSource()==停止接收)
{
開始接收.setBackground(Color.gray);
停止接收.setBackground(Color.blue);
thread.interrupt();
停止=true;
}
}
public void run()
{
while(true)
{
byte data[]=new byte[8192];
DatagramPacket packet=null;
packet=new DatagramPacket(data,data.length,group,port);
try
{
socket.receive(packet);
String message=new String(packet.getData(),0,packet.getLength());
顯示正在接收內容.setText("正在接收的內容:\n"+message);
顯示已接收的內容.append(message+"\n");
}
catch(Exception e)
{
}
if(停止==true)
{
break;
}
}
}
public static void main(String args[])
{
new Receive();
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -