一.使用展示
1.运行代码,首选输入需要连接的局域网IP地址(不输入默认为本机127.0.0.1)
2.确定后进入聊天界面
这是System.out.println()打印的内容
?
?二.完整源代码(详细注解) 复制黏贴即可运行
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.DatagramSocket;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @Author Student
* @date 2021/8/10 8:34
*/
public class ChatUDPClient extends JFrame {
public static void main(String[] args) {
ChatUDPClient chatFrame = new ChatUDPClient();
}
private JTextField sendField;
private JButton sendButton;
private JTextArea msgArea;
private StringBuilder stringBuilder;
private SimpleDateFormat dateFormat;
private JScrollPane scrollPane;
private String ip;
public ChatUDPClient() {
//得到屏幕长宽,为了将界面置于桌面的中央
int screenWidth = (int) this.getToolkit().getScreenSize().getWidth();
int screenHeight = (int) this.getToolkit().getScreenSize().getHeight();
int width = 320;
int height = 380;
int x = (screenWidth - width) / 2;
int y = (screenHeight - height) / 2;
this.setLocation(x, y);
this.setTitle("聊天框");
this.setLayout(null);
init();
this.setSize(width, height);
this.setResizable(false);
this.setVisible(true);
}
public void init() {
//ip:保存输入的ip地址
ip = JOptionPane.showInputDialog("请输入连接的IP地址");
//输入框
sendField = new JTextField();
sendField.setBounds(0, 300, 230, 50);
sendField.setFont(new Font("宋体", Font.BOLD, 25));
this.add(sendField);
//发送按钮
sendButton = new JButton("发送");
sendButton.setBounds(235, 300, 70, 50);
this.add(sendButton);
//存放JTextArea 使有文本有滚轮
scrollPane = new JScrollPane();
scrollPane.setBounds(0, 0, 300, 295);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.add(scrollPane);
//用来展示聊天内容(通信内容)
msgArea = new JTextArea();
msgArea.setBounds(0, 0, 300, 295);
msgArea.setFont(new Font("宋体", Font.BOLD, 20));
msgArea.setEditable(false);
scrollPane.setViewportView(msgArea);
//StringBuilder用来存放聊天的内容,本机内容与他机内容
stringBuilder = new StringBuilder();
//用来格式化时间
dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
//发送按钮添加监听器 用来执行发送消息的线程
sendButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String text = sendField.getText();
//如果发送文本不为空,执行发送
if (text.length() != 0) {
String format = dateFormat.format(new Date());
//StringBuilder添加发送时间和换行
stringBuilder.append(format);
stringBuilder.append("\r\n");
//StringBuilder添加本机发送内容和换行
stringBuilder.append("本机:" + text);
stringBuilder.append("\r\n");
}
//设置文本域展示展示聊天内容
msgArea.setText(stringBuilder.toString());
//开启发送消息线程
new SendMsg().start();
}
});
//默认一直开启消息接收线程
new ReceiveMsg().start();
}
/**
* 消息发送线程类
*/
class SendMsg extends Thread {
public SendMsg() {
}
@Override
public void run() {
this.sendMsg();
}
public void sendMsg() {
DatagramSocket datagramSocket = null;
try {
//创建数据
datagramSocket = new DatagramSocket(8888);
String text = sendField.getText();
//如果发送文本不为空 则发送消息
if (text.length() != 0) {
byte[] bytes = text.getBytes();
//通过ip创建 inderAddress对象
InetAddress inetAddress = InetAddress.getByName(ip);
//常见数据报包
DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, inetAddress, 8889);
//发送数据报包
datagramSocket.send(datagramPacket);
//像控制台输出内容 用于调试
System.out.println("发送的消息为:" + text);
//将发送文本制空 为了下次输入
sendField.setText("");
}
} catch (Exception se) {
se.printStackTrace();
} finally {
if (datagramSocket != null) {
datagramSocket.close();
}
}
}
}
/**
* 消息接收线程
*/
class ReceiveMsg extends Thread {
public ReceiveMsg() {
}
@Override
public void run() {
this.receiveMsg();
}
public void receiveMsg() {
DatagramSocket datagramSocket = null;
try {
//消息接收端口为8889
datagramSocket = new DatagramSocket(8889);
while (true) {
byte[] bytes = new byte[1024];
//创建接收信息的数据报包
DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
//向控制台输出内容 用于调试程序
System.out.println("等待接收消息");
datagramSocket.receive(datagramPacket);
System.out.println("消息接收成功");
//打印收到消息的ip地址
System.out.println(datagramPacket.getAddress());
byte[] data = datagramPacket.getData();
System.out.println(new String(data));
String format = dateFormat.format(new Date());
//StringBuilder添加接收时间和换行
stringBuilder.append(format);
stringBuilder.append("\r\n");
//StringBuilder添加接收的消息和换行
stringBuilder.append("他机:" + new String(data));
stringBuilder.append("\r\n");
//设置文本域展示展示聊天内容
msgArea.setText(stringBuilder.toString());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (datagramSocket != null) {
datagramSocket.close();
}
}
}
}
}
?三.总结
3.1使用了Java Swing? UDP通信? 线程 。简单的一个小案例。
写的比较粗糙,大家看一乐
?
|