1 Star 0 Fork 3

BillchenVip/JAVABASE

forked from wts286010056/JAVABASE 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
BroadCast.java 2.92 KB
一键复制 编辑 原始数据 按行查看 历史
wts286010056 提交于 2019-11-27 10:54 . 增加dao参考网址
package cn.edu.shengda;
//https://www.cnblogs.com/tdcqma/p/4763952.html
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class BroadCast extends JFrame implements ActionListener {
JTextArea textArea;
JTextField textField;
JButton button;
int port=5858;
InetAddress group=null;
MulticastSocket socket=null;
BroadCast(String title) {
super(title);
this.setBounds(0,0,800,600);
this.setLayout(new FlowLayout());
textArea=new JTextArea(10,10);
JLabel label=new JLabel("请输入想发送的话:");
textField=new JTextField(10);
button=new JButton("发送");
button.addActionListener(this);
this.add(textArea);
this.add(label);
this.add(textField);
this.add(button);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
group=InetAddress.getByName("239.255.8.0");
socket=new MulticastSocket(port);
socket.setTimeToLive(1);
socket.joinGroup(group);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
MulticastRead thread=new MulticastRead();
thread.start();
}
class MulticastRead extends Thread{
@Override
public void run() {
while(true)
{
byte[] data=new byte[1024];
DatagramPacket packet=new DatagramPacket(data,data.length);
try {
socket.receive(packet);
String text=new String(packet.getData());
textArea.append(text.trim()+"\r \n");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
public static void main(String[] args){
BroadCast bc=new BroadCast("广播窗口");
bc.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String text=textField.getText();
textArea.append(text+'\n');
DatagramPacket packet=null;
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sd.format(new Date());
String sendText=new String(text+dateStr);
byte data[]=sendText.getBytes();
packet=new DatagramPacket(data,data.length,group,port);
System.out.println(new String(data));
try {
socket.send(packet);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/billchenvip/JAVABASE.git
git@gitee.com:billchenvip/JAVABASE.git
billchenvip
JAVABASE
JAVABASE
master

搜索帮助