【Java网络编程(二)】UDP案例——在线咨询
生活随笔
收集整理的這篇文章主要介紹了
【Java网络编程(二)】UDP案例——在线咨询
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
先運行接收端,再運行發送端
1、簡單的發送與接收
接收端
package cn.hanquan.test;import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress;/** --------------接收端--------------* 1、使用DatagramSocket指定端口 創建接收端* 2、準備容器 封裝成DatagramPacket包裹* 3、阻塞式接收包裹receive(DatagramPacket p)* 4、分析數據 操作的是字節數組* byte[] getData()* byte[] getLength()* 5、釋放資源*/ public class UDPServer {public static void main(String[] args) throws IOException {System.out.println("接收方啟動中~~~");// 1、使用DatagramSocket指定端口 創建接收端DatagramSocket server = new DatagramSocket(9999);// 2、準備容器 封裝成DatagramPacket包裹byte[] container = new byte[1024 * 60];DatagramPacket packet = new DatagramPacket(container, 0, container.length,new InetSocketAddress("localhost", 8888));// 3、阻塞式接收包裹receive(DatagramPacket p)server.receive(packet);// 4、分析數據 操作的是字節數組byte[] datas = packet.getData();int len=packet.getLength();System.out.println(new String(datas,0,len));// 5、釋放資源server.close();} }發送端
package cn.hanquan.test;import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress;/** --------------發送端--------------* 1、使用DatagramSocket指定端口 創建發送端* 2、準備數據容器 轉換成字節數組* 3、封裝成DatagramPacket包裹,需要指定目的地(IP地址+端口)* 4、發送包裹 send (DatagramPacket p)* 5、釋放資源*/ public class UDPclient {public static void main(String[] args) throws IOException {System.out.println("發送方啟動中~~~");// 1、使用DatagramSocket指定端口 創建發送端DatagramSocket client = new DatagramSocket(8888);// 2、準備數據容器 轉換成字節數組String data = "你好世界";byte[] datas = data.getBytes();// 3、封裝成DatagramPacket包裹,需要指定目的地(IP地址+端口)DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost", 9999));// 4、發送包裹 send (DatagramPacket p)client.send(packet);// 5、釋放資源client.close();} }運行結果
2、傳輸基本數據類型
package cn.hanquan.test;import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress;/** --------------發送端--------------* 基本數據類型* 1、使用DatagramSocket指定端口 創建發送端* 2、將基本類型數據 轉換成字節數組* 3、封裝成DatagramPacket包裹,需要指定目的地(IP地址+端口)* 4、發送包裹 send (DatagramPacket p)* 5、釋放資源*/ public class UDPclient {public static void main(String[] args) throws IOException {System.out.println("發送方啟動中~~~");// 1、使用DatagramSocket指定端口 創建發送端DatagramSocket client = new DatagramSocket(8888);// 2、將基本類型數據 轉換成字節數組ByteArrayOutputStream baos = new ByteArrayOutputStream();// DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(baos));DataOutputStream dos = new DataOutputStream(baos);dos.writeUTF("編碼辛酸淚");dos.writeInt(888);dos.flush();byte[] datas = baos.toByteArray();System.out.println("數據長度:" + datas.length);// 3、封裝成DatagramPacket包裹,需要指定目的地(IP地址+端口)DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost", 9999));// 4、發送包裹 send (DatagramPacket p)client.send(packet);// 5、釋放資源client.close();} }接收端
package cn.hanquan.test;import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress;/** --------------接收端--------------* 基本類型數據* 1、使用DatagramSocket指定端口 創建接收端* 2、準備容器 封裝成DatagramPacket包裹* 3、阻塞式接收包裹receive(DatagramPacket p)* 4、分析數據 將字節數組還原為對應的基本類型* byte[] getData()* byte[] getLength()* 5、釋放資源*/ public class UDPServer {public static void main(String[] args) throws IOException {System.out.println("接收方啟動中~~~");// 1、使用DatagramSocket指定端口 創建接收端DatagramSocket server = new DatagramSocket(9999);// 2、準備容器 封裝成DatagramPacket包裹byte[] container = new byte[1024 * 60];DatagramPacket packet = new DatagramPacket(container, 0, container.length,new InetSocketAddress("localhost", 8888));// 3、阻塞式接收包裹receive(DatagramPacket p)server.receive(packet);// 4、分析數據 將字節數組還原為對應的基本類型byte[] datas = packet.getData();DataInputStream dis = new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(datas)));String msg = dis.readUTF();int num = dis.readInt();System.out.println(msg + num);System.out.println("數據長度:" + datas.length);// 5、釋放資源server.close();} }3、傳輸自定義類
需要用到序列化、反序列化
UDPserver.java
package cn.hanquan.test;import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress;/** --------------接收端--------------* 基本類型數據* 1、使用DatagramSocket指定端口 創建接收端* 2、準備容器 封裝成DatagramPacket包裹* 3、阻塞式接收包裹receive(DatagramPacket p)* 4、分析數據 將字節數組還原為對應的基本類型* byte[] getData()* byte[] getLength()* 5、釋放資源*/ public class UDPServer {public static void main(String[] args) throws IOException, ClassNotFoundException {System.out.println("接收方啟動中<<<---");// 1、使用DatagramSocket指定端口 創建接收端DatagramSocket server = new DatagramSocket(9999);// 2、準備容器 封裝成DatagramPacket包裹byte[] container = new byte[1024 * 60];DatagramPacket packet = new DatagramPacket(container, 0, container.length,new InetSocketAddress("localhost", 8888));// 3、阻塞式接收包裹receive(DatagramPacket p)server.receive(packet);// 4、分析數據 將字節數組還原為對應的基本類型byte[] datas = packet.getData();System.out.println("數據長度:" + datas.length);DataInputStream dis = new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(datas)));ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(dis));Person p = (Person) ois.readObject();String msg = ois.readUTF();int num = ois.readInt();System.out.println(p);System.out.println(msg);System.out.println(num);// 5、釋放資源server.close();} }UDPclient.java
package cn.hanquan.test;import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress;/** --------------發送端--------------* 基本數據類型* 1、使用DatagramSocket指定端口 創建發送端* 2、將基本類型數據 轉換成字節數組* 3、封裝成DatagramPacket包裹,需要指定目的地(IP地址+端口)* 4、發送包裹 send (DatagramPacket p)* 5、釋放資源*/ public class UDPclient {public static void main(String[] args) throws IOException {System.out.println("--->>>發送方啟動中");// 1、使用DatagramSocket指定端口 創建發送端DatagramSocket client = new DatagramSocket(8888);// 2、將基本類型數據 轉換成字節數組ByteArrayOutputStream baos = new ByteArrayOutputStream();// DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(baos));DataOutputStream dos = new DataOutputStream(baos);ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(baos));Person p = new Person(36, "魔鬼魚");oos.writeObject(p);oos.writeUTF("編碼辛酸淚");oos.writeInt(888);dos.flush();oos.flush();byte[] datas = baos.toByteArray();// 3、封裝成DatagramPacket包裹,需要指定目的地(IP地址+端口)DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost", 9999));// 4、發送包裹 send (DatagramPacket p)client.send(packet);// 5、釋放資源client.close();} }Person.java
package cn.hanquan.test;import java.io.Serializable;public class Person implements Serializable {int id;String name;public Person(int id, String name) {this.id = id;this.name = name;}@Overridepublic String toString() {return "[ " + id + " " + name + " ]";} }運行結果
4、傳輸文件
UDPclient.java
package cn.hanquan.test;import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress;// 發送端 public class UDPclient {public static void main(String[] args) throws IOException {System.out.println("--->>>發送方啟動中");// 1、使用DatagramSocket指定端口 創建發送端DatagramSocket client = new DatagramSocket(8888);// 2、將文件轉換成字節數組byte[] datas = IOutils.fileToByteArray("頭像.jpg");// 3、封裝成DatagramPacket包裹,需要指定目的地(IP地址+端口)DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost", 9999));// 4、發送包裹 send (DatagramPacket p)client.send(packet);// 5、釋放資源client.close();} }UDPServer.java
package cn.hanquan.test;import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress;// 接收端 public class UDPServer {public static void main(String[] args) throws IOException, ClassNotFoundException {System.out.println("接收方啟動中<<<---");// 1、使用DatagramSocket指定端口 創建接收端DatagramSocket server = new DatagramSocket(9999);// 2、準備容器 封裝成DatagramPacket包裹byte[] container = new byte[1024 * 60];DatagramPacket packet = new DatagramPacket(container, 0, container.length,new InetSocketAddress("localhost", 8888));// 3、阻塞式接收包裹receive(DatagramPacket p)server.receive(packet);// 4、分析數據 將字節數組還原為對應的文件byte[] datas = packet.getData();IOutils.byteArrayToFile("new.jpg", datas);// 5、釋放資源server.close();} }IOutils.java
package cn.hanquan.test;import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream;public class IOutils {public static byte[] fileToByteArray(String filePath) throws IOException {// 1、創建源于目的地File src = new File(filePath);// 2、選擇流InputStream is = null;ByteArrayOutputStream baos = null;is = new FileInputStream(src);baos = new ByteArrayOutputStream();// 3、操作(分段讀取)byte[] flush = new byte[1024 * 10];// 緩沖容器int len = -1;while ((len = is.read(flush)) != -1) {baos.write(flush, 0, len);}baos.flush();is.close();return baos.toByteArray();}public static void byteArrayToFile(String filePath, byte[] bytearray) throws IOException {// 創建源File tofile = new File(filePath);// 選擇流ByteArrayInputStream instream = new ByteArrayInputStream(bytearray);FileOutputStream outstream = new FileOutputStream(tofile);// 操作byte[] flush = new byte[1024 * 10];int len = -1;while ((len = instream.read(flush)) != -1) {outstream.write(flush, 0, len);}// 關閉流outstream.close();} }運行結果:圖片成功接收
5、單方向多次發送
發送方
package cn.hanquan.test;import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress;// 發送端 public class UDPclient {public static void main(String[] args) throws IOException {System.out.println("--->>>發送方啟動中");// 1、使用DatagramSocket指定端口 創建發送端DatagramSocket client = new DatagramSocket(7777);// 2、轉換成字節數組BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));while (true) {String data = reader.readLine();byte[] datas = data.getBytes();// 3、封裝成DatagramPacket包裹,需要指定目的地(IP地址+端口)DatagramPacket packet = new DatagramPacket(datas, 0, datas.length,new InetSocketAddress("localhost", 9999));// 4、發送包裹 send (DatagramPacket p)client.send(packet);if (data.equals("q"))break;}// 5、釋放資源client.close();} }接收方
package cn.hanquan.test;import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress;// 接收端 public class UDPServer {public static void main(String[] args) throws IOException, ClassNotFoundException {System.out.println("接收方啟動中<<<---");// 1、使用DatagramSocket指定端口 創建接收端DatagramSocket server = new DatagramSocket(9999);while (true) {// 2、準備容器 封裝成DatagramPacket包裹byte[] container = new byte[1024 * 60];DatagramPacket packet = new DatagramPacket(container, 0, container.length,new InetSocketAddress("localhost", 7777));// 3、阻塞式接收包裹receive(DatagramPacket p)server.receive(packet);// 4、分析數據 將字節數組還原為對應的字符串byte[] datas = packet.getData();int len = packet.getLength();String str = new String(datas, 0, len);System.out.println(str);if (str.equals("q"))break;}// 5、釋放資源server.close();} }6、雙向多次發送
既然是雙向,就沒有發送方與接收方的區別了。為了便于描述,我們用client端與server端來區分。
client端
package cn.hanquan.test;import java.io.IOException;// 發送端 public class UDPclient {public static void main(String[] args) throws IOException {System.out.println("----我是大傻子----");new Thread(new ClientSend()).start();new Thread(new ClientReceive()).start();} }class ClientSend implements Runnable {@Overridepublic void run() {try {UDPutils.send("localhost", 6666, 5555);} catch (IOException e) {e.printStackTrace();}} }class ClientReceive implements Runnable {@Overridepublic void run() {try {UDPutils.receive("localhost", 8888, 7777);} catch (IOException e) {e.printStackTrace();}} }server端
package cn.hanquan.test;import java.io.IOException;// 接收端 public class UDPServer {public static void main(String[] args) throws IOException, ClassNotFoundException {System.out.println("----我是程序猿----");new Thread(new ServerSend()).start();new Thread(new ServerReceive()).start();} }class ServerSend implements Runnable {@Overridepublic void run() {try {UDPutils.send("localhost", 7777, 8888);} catch (IOException e) {e.printStackTrace();}} }class ServerReceive implements Runnable {@Overridepublic void run() {try {UDPutils.receive("localhost", 5555, 6666);} catch (IOException e) {e.printStackTrace();}} }工具類
package cn.hanquan.test;import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress;public class UDPutils {public static void receive(String name, int myPort, int hisPort) throws IOException {System.out.println(name + " is receiving... myPort=" + myPort + " hisPort=" + hisPort);// 1、使用DatagramSocket指定端口 創建接收端DatagramSocket server = new DatagramSocket(myPort);while (true) {// 2、準備容器 封裝成DatagramPacket包裹byte[] container = new byte[1024 * 60];DatagramPacket packet = new DatagramPacket(container, 0, container.length,new InetSocketAddress(name, hisPort));// 3、阻塞式接收包裹receive(DatagramPacket p)server.receive(packet);// 4、分析數據 將字節數組還原為對應的文件byte[] datas = packet.getData();int len = packet.getLength();String str = new String(datas, 0, len);System.out.println(str);if (str.equals("q"))break;}}public static void send(String name, int myPort, int hisPort) throws IOException {System.out.println(name + " is sending... myPort=" + myPort + " hisPort=" + hisPort);// 1、使用DatagramSocket指定端口 創建發送端DatagramSocket client = new DatagramSocket(myPort);// 2、將文件轉換成字節數組BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));while (true) {String data = reader.readLine();byte[] datas = data.getBytes();// 3、封裝成DatagramPacket包裹,需要指定目的地(IP地址+端口)DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(name, hisPort));// 4、發送包裹 send (DatagramPacket p)client.send(packet);if (data.equals("q"))break;}} }運行結果
總結
以上是生活随笔為你收集整理的【Java网络编程(二)】UDP案例——在线咨询的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Java网络编程(一)】IP地址、端口
- 下一篇: 【Java网络编程(三)】TCP的使用—