您好,登錄后才能下訂單哦!
這篇文章主要講解了“Java網絡編程UDP的實現原理”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Java網絡編程UDP的實現原理”吧!
UDP實現通信非常簡單,沒有服務器,每個都是客戶端,每個客戶端都需要一個發送端口和一個接收端口。一個客戶端向另一個客戶端發送消息時,需要知道對方的IP和接收端口,所用到的類為DatagramSocket。
DatagramSocket socket =new DatagramSocket(),發送端socket,若不指定端口,系統自動分配
DatagramSocket socket =new DatagramSocket("接收信息端口"),接收端socket,需要指定接收端口
若想客戶端之間進行全雙工通信,每個客戶端都要有兩個線程,一個用于發送信息,一個用于接收信息。
那么UDP怎么實現私聊和群聊呢?(在本機一臺電腦的情況下實現)
首先私聊,客戶端向另一個客戶端發送消息,就要知道其IP(本機都是固定的localhost)和接收端口,也需要姓名進行標識,所以,每個客戶端都至少要自己的姓名和接收端口,而且端口不可重復,否則會報端口被占用的錯。
其次群聊,由于在本機一臺電腦上進行,接收端口各不相同,所以廣播就不行了,此時就希望每個客戶端在啟動的時候,能夠把自己的姓名和接收端口給存起來,然后就可以遍歷進行群聊。
實現:
第一種,在每個客戶端啟動時,輸入自己的姓名和接收端口,發送信息時,需要輸入對方的接收端口號,如果輸入時輸入了多個端口,就是群發。那么這樣每次發送信息時都要指定對方的端口。。。
第二種,客戶端啟動時,輸入姓名和接收端口,此時就把數據存起來,發送信息時,只用指定對方姓名即可。。。可用數據庫存,可用文件存,我用的是XML來存。
要創建xml文件,路徑在Operation類中
UdpClient.java:
public class UdpClient { public static void main(String[] args) { try { Scanner scanner = new Scanner(System.in); User user = new User(); System.out.print("請輸入用戶名》》"); String userName = scanner.next(); if (Operation.userIsExist(userName)) { //如果此用戶已經注冊過,直接把注冊時用的接收端口分配給他 user = Operation.findUserByName(userName); }else { //未注冊,用戶自己指定端口 while(true) { System.out.println("請輸入接收端口》》"); int port = Integer.parseInt(scanner.next()); if (Operation.portIsExist(port)) { System.err.println("該端口已被使用,請重新輸入。。。。"); continue; }else { user.setName(userName); user.setPort(port); Operation.addUser(user); break; } } } new Thread(new SendMsg(user)).start(); new Thread(new ReceiveMsg(user)).start(); } catch (Exception e) { e.printStackTrace(); } } }
發送信息:
public class SendMsg implements Runnable{ private User self = null; private DatagramSocket socket = null; private BufferedReader reader = null; public SendMsg(User self) { try { socket = new DatagramSocket(); reader = new BufferedReader(new InputStreamReader(System.in)); this.self = self; } catch (Exception e) { e.printStackTrace(); } } @Override public void run() { try { while(true) { String[] msg = reader.readLine().split("@"); if (msg.length != 2) { System.err.println("注意格式:消息@對方名字(私聊)或all(群聊)"); continue; } msg[0] = self.getName()+"說:"+msg[0]; byte[] data = msg[0].getBytes(); String toPerson = msg[1]; if (("all").equals(toPerson)) { //群聊,獲取所有用戶,不管對方在不在線,都發過去 List<User> users = Operation.getUsers(); for(User user:users) { if (self != user) { DatagramPacket packet = new DatagramPacket(data, 0,data.length,new InetSocketAddress("localhost",user.getPort())); socket.send(packet); } } }else { //私聊 try { DatagramPacket packet = new DatagramPacket(data, 0,data.length,new InetSocketAddress("localhost",Operation.findUserByName(toPerson).getPort())); socket.send(packet); } catch (Exception e) { System.out.println("對方不在線。。。"); } } } } catch (Exception e) { e.printStackTrace(); } } }
接收消息:
public class ReceiveMsg implements Runnable{ private DatagramSocket socket = null; public ReceiveMsg(User user) { try { socket = new DatagramSocket(user.getPort()); } catch (Exception e) { e.printStackTrace(); } } @Override public void run() { try { while(true) { //準備接收包裹 byte[] container = new byte[1024]; DatagramPacket packet = new DatagramPacket(container,0,container.length); socket.receive(packet); byte[]data = packet.getData(); String receiveData = new String(data, 0, data.length); System.out.println(receiveData); } } catch (Exception e) { e.printStackTrace(); } socket.close(); } }
操作XML文件類:
public class Operation { private static String FILE_PATH = "config/user.xml"; //文件目錄 //在xml文件中添加一個用戶信息 public static void addUser(User user) { InputStream in = null; SAXReader reader = new SAXReader(); Document doc = null; try { in = new FileInputStream(FILE_PATH); doc = reader.read(in); Element root = doc.getRootElement(); //獲取xml根節點,即users節點 Element element = root.addElement("user"); element.addElement("name").addText(user.getName()); element.addElement("port").addText(String.valueOf(user.getPort())); FileOutputStream fos = new FileOutputStream(FILE_PATH); //格式化xml文件 OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("utf-8"); XMLWriter writer = new XMLWriter(fos,format); writer.write(doc); writer.close(); } catch (Exception e) { System.out.println("error"); } finally { try { if(in != null) in.close(); } catch (IOException e) { System.out.println("error"); } } } //列出xml中所有用戶信息 public static List<User> getUsers() { InputStream in = null; SAXReader reader = new SAXReader(); Document doc = null; List<User> users = new ArrayList<>(); try { in = new FileInputStream(FILE_PATH); doc = reader.read(in); Element root = doc.getRootElement(); List<Element> elements = root.elements(); for (Element element : elements) { User user = new User(); user.setName(element.elementText("name")); user.setPort(Integer.valueOf(element.elementText("port"))); users.add(user); } } catch (Exception e1) { System.out.println("error"); } finally { try { in.close(); } catch (IOException e) { System.out.println("error"); } } return users; } public static User findUserByName(String name) { InputStream in = null; SAXReader reader = new SAXReader(); Document doc = null; try { in = new FileInputStream(FILE_PATH); doc = reader.read(in); Element root = doc.getRootElement(); List<Element> elements = root.elements(); for (Element element : elements) { if(name != null && name.equals(element.elementText("name"))) { User user = new User(); user.setName(name); user.setPort(Integer.parseInt(element.elementText("port"))); return user; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } return null; } public static boolean portIsExist(int port) { InputStream in = null; SAXReader reader = new SAXReader(); Document doc = null; try { in = new FileInputStream(FILE_PATH); doc = reader.read(in); Element root = doc.getRootElement(); List<Element> elements = root.elements(); for (Element element : elements) { if(port == Integer.parseInt(element.elementText("port"))) return true; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } return false; } //判斷某個用戶是否存在該xml中 public static boolean userIsExist(String name) { InputStream in = null; SAXReader reader = new SAXReader(); Document doc = null; try { in = new FileInputStream(FILE_PATH); doc = reader.read(in); Element root = doc.getRootElement(); List<Element> elements = root.elements(); for (Element element : elements) { if(name != null && name.equals(element.elementText("name"))) return true; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } return false; } }
用戶實體類:
public class User implements Serializable{ private String name;//姓名 private int port;//接收端口 public String getName() { return name; } public int getPort() { return port; } public void setName(String name) { this.name = name; } public void setPort(int port) { this.port = port; } @Override public String toString() { return "User [name=" + name + ", port=" + port + "]"; } }
運行結果:
感謝各位的閱讀,以上就是“Java網絡編程UDP的實現原理”的內容了,經過本文的學習后,相信大家對Java網絡編程UDP的實現原理這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。