代码部分--UDP传输
* 1.发送Send
* 创建DatagramSocket, 随机端口号
* 创建DatagramPacket, 指定数据, 长度, 地址, 端口
* 使用DatagramSocket发送DatagramPacket
* 关闭DatagramSocket
package demo1;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.SocketException;public class Test_send { /** 1.发送Send * 创建DatagramSocket, 随机端口号 * 创建DatagramPacket, 指定数据, 长度, 地址, 端口 * 使用DatagramSocket发送DatagramPacket * 关闭DatagramSocket * @throws SocketException */public static void main(String[] args) throws Exception { //定义要传输的字符串 String str="hahhah"; //创建socket DatagramSocket socket=new DatagramSocket(); //创建packet() DatagramPacket packet =new DatagramPacket(str.getBytes(), str.getBytes().length,InetAddress.getByName("127.0.0.1"),6666); //发送数据 socket.send(packet); //关闭socket socket.close(); }}
* 2.接收Receive
* 创建DatagramSocket, 指定端口号
* 创建DatagramPacket, 指定数组, 长度
* 使用DatagramSocket接收DatagramPacket
* 关闭DatagramSocket
* 从DatagramPacket中获取数据
package demo1;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.SocketException;public class Test_receiver { /** 创建DatagramSocket, 指定端口号 * 创建DatagramPacket, 指定数组, 长度 * 使用DatagramSocket接收DatagramPacket * 关闭DatagramSocket * 从DatagramPacket中获取数据 * @throws Exception */public static void main(String[] args) throws Exception { //创建socket相当有码头 DatagramSocket socket=new DatagramSocket(6666); //创建packet相当于集装箱 DatagramPacket packet=new DatagramPacket(new byte[1024],1024); //获取数据 socket.receive(packet); //关闭socket socket.close(); //从packet中取出数据 byte[] data=packet.getData(); System.out.println(new String(data,0,packet.getLength())); }}
UDP传输优化(不断的发送,接收)
package demo1;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.SocketException;import java.util.Scanner;public class Test_send { /** * 1.发送Send 创建DatagramSocket, 随机端口号 创建DatagramPacket, 指定数据, 长度, 地址, 端口 * 使用DatagramSocket发送DatagramPacket 关闭DatagramSocket * * @throws SocketException */ public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); // 创建socket DatagramSocket socket = new DatagramSocket(); while (true) { String line = in.nextLine(); if ("quit".equals(line)) { break; } else { // 创建packet() DatagramPacket packet = new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getByName("127.0.0.1"), 6666); // 发送数据 socket.send(packet); } } // 关闭socket socket.close(); }}
package demo1;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.SocketException;public class Test_receiver { /** 创建DatagramSocket, 指定端口号 * 创建DatagramPacket, 指定数组, 长度 * 使用DatagramSocket接收DatagramPacket * 关闭DatagramSocket * 从DatagramPacket中获取数据 * @throws Exception */public static void main(String[] args) throws Exception { //创建socket相当有码头 DatagramSocket socket=new DatagramSocket(6666); //创建packet相当于集装箱 DatagramPacket packet=new DatagramPacket(new byte[1024],1024); while(true) { //获取数据 socket.receive(packet); //从packet中取出数据 byte[] data=packet.getData(); //获取ip String ip=packet.getAddress().getHostAddress(); System.out.println("ip:"+ip+" :"+new String(data,0,packet.getLength())); } }}
* 3.接收方获取ip和端口号
* String ip = packet.getAddress().getHostAddress();
* int port = packet.getPort();
UDP传输优化(多线程)
package demo1;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.SocketException;import java.util.Scanner;public class Test_send { /** * 1.发送Send 创建DatagramSocket, 随机端口号 创建DatagramPacket, 指定数据, 长度, 地址, 端口 * 使用DatagramSocket发送DatagramPacket 关闭DatagramSocket * * @throws SocketException */ public static void main(String[] args) throws Exception { new Receive().start(); new Send().start(); }}class Send extends Thread{ public void run() { try { Scanner in = new Scanner(System.in); // 创建socket DatagramSocket socket; socket = new DatagramSocket(); while (true) { String line = in.nextLine(); if ("quit".equals(line)) { break; } else { // 创建packet() DatagramPacket packet = new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getByName("127.0.0.1"), 9999); // 发送数据 socket.send(packet); } } // 关闭socket socket.close(); } catch (Exception e) { e.printStackTrace(); } }}class Receive extends Thread{ public void run() { try { //创建socket相当有码头 DatagramSocket socket=new DatagramSocket(9999); //创建packet相当于集装箱 DatagramPacket packet=new DatagramPacket(new byte[1024],1024); while(true) { //获取数据 socket.receive(packet); //从packet中取出数据 byte[] data=packet.getData(); //获取ip String ip=packet.getAddress().getHostAddress(); System.out.println("ip:"+ip+" :"+new String(data,0,packet.getLength())); } }catch (IOException e) { e.printStackTrace(); } }}
UDP优化-GUI界面聊天(显示+关闭+发送)
界面
代码实现
package demo2;import java.awt.BorderLayout;import java.awt.Button;import java.awt.Font;import java.awt.Frame;import java.awt.Panel;import java.awt.TextArea;import java.awt.TextField;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.SocketException;import java.text.SimpleDateFormat;import java.util.Date;public class GUIDemo extends Frame { TextField ip; Button send; Button log; Button clear; Button shake; TextArea show; TextArea edit; DatagramSocket socket; /** * 窗体的初始化 */ public GUIDemo() { // 基本控件的初始化 init(); try { socket = new DatagramSocket(); } catch (SocketException e) { e.printStackTrace(); } // 南边panel的初始化 sourceMade(); // 中间panel的初始化 centerMade(); // 事件添加 event(); } /** * 中间panel构建 */ public void centerMade() { Panel center = new Panel(); center.setLayout(new BorderLayout()); show = new TextArea(); show.setEditable(false); show.setFont(new Font("xxx", Font.PLAIN, 15)); edit = new TextArea(); edit.setFont(new Font("xxx", Font.PLAIN, 15)); center.add(show, BorderLayout.CENTER); center.add(edit, BorderLayout.SOUTH); this.add(center, BorderLayout.CENTER); } /** * 南边窗体初始化 */ public void sourceMade() { Panel source = new Panel(); ip = new TextField(15); ip.setText("127.0.0.1"); send = new Button("发送"); log = new Button("记录"); clear = new Button("清屏"); shake = new Button("震动"); source.add(ip); source.add(send); source.add(log); source.add(clear); source.add(shake); this.add(source, BorderLayout.SOUTH); } public void init() { this.setLocation(500, 500); this.setSize(400, 600); new Receive().start(); this.setVisible(true); } public void event() { // 关闭窗体事件 this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { socket.close(); System.exit(0); } }); // 发送事件 send.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { send(); } catch (IOException e1) { e1.printStackTrace(); } } }); // 记录事件 // 清屏事件 // 震动事件 } public void send() throws IOException { String message = edit.getText(); String host = ip.getText(); DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(host), 9999); socket.send(packet); String time = getCurrentTime(); show.append(time + "我对" + host + "说:\r\n" + message + "\r\n\r\n"); edit.setText(""); } private String getCurrentTime() { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); return sdf.format(date); } public static void main(String[] args) { GUIDemo demo = new GUIDemo(); } private class Receive extends Thread { public void run() { try { DatagramSocket socket = new DatagramSocket(9999); DatagramPacket packet = new DatagramPacket(new byte[1024], 1024); while (true) { socket.receive(packet); String message = new String(packet.getData(), 0, packet.getLength()); String time = getCurrentTime(); String ipstr = packet.getAddress().getHostAddress(); show.append(time + " " + ipstr + " 对我说:\r\n" + message + "\r\n\r\n"); } } catch (Exception e) { e.printStackTrace(); } } }}
UDP优化-GUI界面聊天(记录+清屏+震动)
清屏
clear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { show.setText(""); } });
记录
// 记录事件 log.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { logFile(); } catch (Exception e1) { e1.printStackTrace(); } } });
public void logFile() throws Exception { bw.flush(); //获取输入流 FileInputStream fis=new FileInputStream("src/log.txt"); //创建缓冲区 ByteArrayOutputStream baos=new ByteArrayOutputStream(); int len; byte arr[]=new byte[8192]; while((len=fis.read(arr))!=-1) { baos.write(arr,0,len); } String str=baos.toString(); show.setText(str); }
震动
// 震动事件 shake.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { send(new byte[]{-1},ip.getText()); } catch (Exception e1) { e1.printStackTrace(); } } });
public void shake() { int x=getLocation().x; int y=getLocation().y; for(int i=0;i<3;i++) { try { this.setLocation(x+10,y+10); Thread.sleep(20); this.setLocation(x+10,y-10); Thread.sleep(20); this.setLocation(x-10,y+10); Thread.sleep(20); this.setLocation(x-10,y-10); Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } } this.setLocation(x,y); }
UDP优化-GUI界面聊天(快捷键)
//快捷键发送 edit.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { //CTRL+回车====》发送信息 if(e.getKeyChar()==KeyEvent.VK_ENTER && e.isControlDown()) { try { send(); } catch (IOException e1) { e1.printStackTrace(); } } } });
UDP优化-GUI界面聊天(代码优化)
public void send() throws IOException { String message = edit.getText(); String host = ip.getText(); host=((host.trim().length()==0)?"255.255.255.255":host); DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(host), 9999); socket.send(packet); String time = getCurrentTime(); host=(("255.255.255.255").equals(host)?"所有人":host); String str = time + "我对" + host + "说:\r\n" + message + "\r\n\r\n"; show.append(str); bw.append(str); edit.setText(""); }
完整代码
package demo2;import java.awt.BorderLayout;import java.awt.Button;import java.awt.Font;import java.awt.Frame;import java.awt.Panel;import java.awt.TextArea;import java.awt.TextField;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.BufferedWriter;import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.FileWriter;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.text.SimpleDateFormat;import java.util.Date;public class GUIDemo extends Frame { TextField ip; Button send; Button log; Button clear; Button shake; TextArea show; TextArea edit; DatagramSocket socket; BufferedWriter bw; /** * 窗体的初始化 */ public GUIDemo() { // 基本控件的初始化 init(); try { socket = new DatagramSocket(); bw=new BufferedWriter(new FileWriter("src/log.txt",true)); } catch (Exception e) { e.printStackTrace(); } // 南边panel的初始化 sourceMade(); // 中间panel的初始化 centerMade(); // 事件添加 event(); } /** * 中间panel构建 */ public void centerMade() { Panel center = new Panel(); center.setLayout(new BorderLayout()); show = new TextArea(); show.setEditable(false); show.setFont(new Font("xxx", Font.PLAIN, 15)); edit = new TextArea(); edit.setFont(new Font("xxx", Font.PLAIN, 15)); center.add(show, BorderLayout.CENTER); center.add(edit, BorderLayout.SOUTH); this.add(center, BorderLayout.CENTER); } /** * 南边窗体初始化 */ public void sourceMade() { Panel source = new Panel(); ip = new TextField(15); ip.setText("192.168.28.1"); send = new Button("发送"); log = new Button("记录"); clear = new Button("清屏"); shake = new Button("震动"); source.add(ip); source.add(send); source.add(log); source.add(clear); source.add(shake); this.add(source, BorderLayout.SOUTH); } public void init() { this.setLocation(500, 500); this.setSize(400, 600); new Receive().start(); this.setVisible(true); } public void event() { // 关闭窗体事件 this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { socket.close(); System.exit(0); } }); // 发送事件 send.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { send(); } catch (IOException e1) { e1.printStackTrace(); } } }); // 记录事件 log.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { logFile(); } catch (Exception e1) { e1.printStackTrace(); } } }); // 清屏事件 clear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { show.setText(""); } }); // 震动事件 shake.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { send(new byte[]{-1},ip.getText()); } catch (Exception e1) { e1.printStackTrace(); } } }); //快捷键发送 edit.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { //CTRL+回车====》发送信息 if(e.getKeyChar()==KeyEvent.VK_ENTER && e.isControlDown()) { try { send(); } catch (IOException e1) { e1.printStackTrace(); } } } }); } public void logFile() throws Exception { bw.flush(); //获取输入流 FileInputStream fis=new FileInputStream("src/log.txt"); //创建缓冲区 ByteArrayOutputStream baos=new ByteArrayOutputStream(); int len; byte arr[]=new byte[8192]; while((len=fis.read(arr))!=-1) { baos.write(arr,0,len); } String str=baos.toString(); show.setText(str); } public void shake() { int x=getLocation().x; int y=getLocation().y; for(int i=0;i<3;i++) { try { this.setLocation(x+10,y+10); Thread.sleep(20); this.setLocation(x+10,y-10); Thread.sleep(20); this.setLocation(x-10,y+10); Thread.sleep(20); this.setLocation(x-10,y-10); Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } } this.setLocation(x,y); } public void send(byte[] arr,String ip) throws IOException { DatagramPacket packet = new DatagramPacket(arr, arr.length, InetAddress.getByName(ip), 9999); socket.send(packet); } public void send() throws IOException { String message = edit.getText(); String host = ip.getText(); host=((host.trim().length()==0)?"255.255.255.255":host); DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(host), 9999); socket.send(packet); String time = getCurrentTime(); host=(("255.255.255.255").equals(host)?"所有人":host); String str = time + "我对" + host + "说:\r\n" + message + "\r\n\r\n"; show.append(str); bw.append(str); edit.setText(""); } private String getCurrentTime() { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); return sdf.format(date); } public static void main(String[] args) { GUIDemo demo = new GUIDemo(); } private class Receive extends Thread { public void run() { try { DatagramSocket socket = new DatagramSocket(9999); DatagramPacket packet = new DatagramPacket(new byte[1024], 1024); while (true) { socket.receive(packet); String message = new String(packet.getData(), 0, packet.getLength()); if(packet.getData()[0]==-1&&packet.getLength()==1) { shake(); continue; } String time = getCurrentTime(); String ipstr = packet.getAddress().getHostAddress(); String str = time + " " + ipstr + " 对我说:\r\n" + message + "\r\n\r\n"; show.append(str); bw.append(str); } } catch (Exception e) { e.printStackTrace(); } } }}
最终界面
封装双击可运行jar包
(1)选中涉及到的java文件
(2)右击,导出
(3)JavFile
(4)next(选择保存路径)
(5)next--next--(选取main所在类)
(6)finash