当前位置:网站首页>NIO BIO AIO
NIO BIO AIO
2022-06-09 09:37:00 【Xiaoxiao is not called Xiaoxiao】
BIO
IO The system of stream class
1、InputStream/OutputStream : Abstract class of byte stream 2、Reader/Writer : Abstract class of character stream 3、FileInputStream/FileOutputStream : Node flow , Direct operation in bytes “ file ” 4、ByteArrayInputStream/ByteArrayOutputStream : Node flow , Direct operation in bytes “ Byte array object ” 5、DataInputStream/DataOutputStream: Data flow , Steerable data types 6、ObjectInputStream/ObjectOutputStream : Processing flow , Direct operation in bytes “ object ” 7、DateInputStream/DateOutputStream : Processing flow , Direct operation in bytes “ Basic data type and string type ” 8、FileReader/FileWriter : Node flow : Direct operation in characters “ text file ”, Be careful : Can only read and write text files 9、BufferedReader/BufferedWriter : Processing flow : take Reader/Writer Objects are packaged , Add cache function , Improve reading and writing efficiency 10、BufferedInputStream/BufferedOutputStream :( Buffer byte stream ) Processing flow , take InputStream/OutputStream Objects are packaged ,, Add cache function , Improve reading and writing efficiency 11、InputStreamReader/OutputStreamWriter : Processing flow : Convert byte stream object to character stream object 12、PrintWriter : Processing flow : take OutputStream For packaging , Can easily output characters , More flexible
File
--> Abstracting files into objects // Operate on files File file = new File("E:/bb.txt"); System.out.println(file.exists()); // Note that only files can be created -->at java.base/java.io.WinNTFileSystem.createFileExclusively(Native Method) System.out.println(file.createNewFile()); System.out.println(file.getName()); System.out.println(file.getPath()); System.out.println(file);--> And getPath() The method has the same effect System.out.println(file.isHidden()); System.out.println(file.isDirectory()); System.out.println(file.isFile()); System.out.println(file.delete()); // Returns the last modified time of the file -->long type , Construct time instances , The output shows the specific time System.out.println(new Date(file.lastModified())); // Returns the number of bytes in the file . The folder can be calculated , Go straight back to 0 System.out.println(file.length()); // Returns a collection of all file and folder names under the file object path String[] list = file.list(); // Returns the of all files and folders under this file object path File A collection of objects File[] files = file.listFiles(); // Rename the file , You need to create a new file in advance File example , And then put the new File Instance incoming method File file1 = new File("E:/aa.txt"); boolean b = file.renameTo(file1); // Operate on the directory File file1 = new File("E:/a/b"); file1.mkdirs(); System.out.println(file1.exists()); System.out.println(file1.isDirectory()); File file2 = new File("E:"); String[] arr = file2.list(); for (String tru : arr) { System.out.println(tru); } File[] arr1 = file2.listFiles(); for (File temp : arr1) { System.out.println(temp); } // Get the parent file class object --> Generated by the parent for the upper path of the current file File Class instance --> Get the parent class instance directly File file = new File("E:/a/aa.txt"); File parentFile = file.getParentFile(); System.out.println(parentFile.getPath()); System.out.println(parentFile.getName()); --> Get the parent file path , To create a File class String parent = file.getParent(); File file1 = new File(parent); System.out.println(file1.getPath()); System.out.println(file1.getName());
FileInputStream
--> File byte stream --> Read data to disk --> No buffer FileInputStream file=null; try { file=new FileInputStream("E:/ test IO flow .txt"); StringBuilder aa = new StringBuilder(); int temp = 0; try { //file.read()--> Bytes read while ((temp = file.read()) != -1) { System.out.println(temp); System.out.println(aa.append((char) temp)); } } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { try { if (file != null) { file.close(); } } catch (IOException e) { e.printStackTrace(); } }
buffer
//--> Mode one FileInputStream file = null; FileOutputStream bb = null; try { file = new FileInputStream("E:/ Screen capture .png"); bb=new FileOutputStream("E:/cc.png"); // Create a cache to store data byte[] f = new byte[1024]; int temp = 0; /** * Every time you store data in an array , Except for the last transmission , The array is filled */ while ((temp = file.read(f)) != -1) { bb.write(f,0,temp); // Write data to memory } // Save the data in memory to disk bb.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { try { if (file==null){ file.close(); } if (bb != null) { bb.close(); } } catch (IOException e) { e.printStackTrace(); } } //--> Mode two FileInputStream file = null; FileOutputStream bb = null; try { file = new FileInputStream("E:/ Screen capture .png"); bb=new FileOutputStream("E:/cc.png"); // Create a cache to store data // You can specify the length or the length of the calling file // When using a given length , Need to use while loop // When using the call file length , No need to use while loop byte[] f = new byte[file.available()]; // take file Read to cache , Then output the data in the cache to the memory file.read(f); // Save the data in memory to disk bb.write(f); bb.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { try { if (file==null){ file.close(); } if (bb != null) { bb.close(); } } catch (IOException e) { e.printStackTrace(); } }
Buffer byte stream
FileInputStream aa = null; BufferedInputStream bb = null; BufferedOutputStream cc = null; FileOutputStream dd = null; try { aa = new FileInputStream("E:/ Screen capture .png"); bb = new BufferedInputStream(aa); dd = new FileOutputStream("E:/bb.png"); cc = new BufferedOutputStream(dd); int temp = 0; // In buffer stream byte The default array length is 8192 // There is memory space between input stream and output stream // After using the buffer stream, you can directly use the buffer stream object to put data into memory while ((temp = bb.read()) != -1) { // After using the buffer stream, you can directly put the data in memory into the buffer stream cc.write(temp); } cc.flush(); } catch (Exception e) { e.printStackTrace(); }finally { // The order of closing the flow : Turn it on and off ( It is related to the order in which the flow object is created , The input stream part comes first , The output stream part is later ) try { if (bb != null) { bb.close(); } if (aa != null) { aa.close(); } if (cc != null) { bb.close(); } if (dd != null) { bb.close(); } } catch (Exception e) { e.printStackTrace(); } }
DataOutputStream
//--> Data output stream ( Processing flow ) DataOutputStream aa = null; try { aa = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("e:/ Data flow .txt"))); aa.writeChar('a'); aa.writeDouble(10.2); aa.writeBoolean(false); aa.writeUTF("yang"); aa.flush(); } catch (Exception e) { e.printStackTrace(); }finally { try { if (aa != null) { aa.close(); } } catch (Exception e) { e.printStackTrace(); } }
DataInputStream
//--> Data input stream DataInputStream aa = null; try { aa = new DataInputStream(new BufferedInputStream(new FileInputStream("E:/ Data flow .txt"))); // The type is read in the same order as it is stored , Otherwise, it cannot be read System.out.println(aa.readChar()); System.out.println(aa.readDouble()); System.out.println(aa.readBoolean()); System.out.println(aa.readUTF()); } catch (Exception e) { e.printStackTrace(); }finally { try { if (aa != null) { aa.close(); } } catch (Exception e) { e.printStackTrace(); } }
ObjectOutputStream
//--> Object flow ( Processing flow )-- Object node output stream -- Write operations to basic data types ObjectOutputStream aa = null; try { aa = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("e:/ Object flow .txt"))); aa.writeChar('a'); aa.writeDouble(Math.random()); aa.writeBoolean(true); aa.writeUTF("jing"); aa.flush(); } catch (Exception e) { e.printStackTrace(); }finally { try { if (aa != null) { aa.close(); } } catch (Exception e) { e.printStackTrace(); } }
ObjectInputStream
//--> Object node input stream --> Read basic data types and serialize and deserialize class objects ObjectInputStream aa = null; try { aa = new ObjectInputStream(new BufferedInputStream(new FileInputStream("E:/ Object flow .txt"))); System.out.println(aa.readChar()); System.out.println(aa.readDouble()); System.out.println(aa.readBoolean()); System.out.println(aa.readUTF()); } catch (Exception e) { e.printStackTrace(); }finally { try { if (aa != null) { aa.close(); } } catch (Exception e) { e.printStackTrace(); } }
InputStreamReader–>OutputStreamWriter
// Used to convert byte stream into character stream BufferedReader aa = null; BufferedWriter bb = null; try { aa = new BufferedReader(new InputStreamReader(System.in)); bb = new BufferedWriter(new OutputStreamWriter(System.out)); while (true) { bb.write(" Please enter by keyboard :"); bb.flush(); // Put keyboard input into variables in memory , Call... When output is convenient String temp = aa.readLine(); if ("exit".equals(temp)) { return; } bb.write(" What you input is :"+temp); bb.newLine(); bb.flush(); } } catch (Exception e) { e.printStackTrace(); }finally { try { if (aa != null) { aa.close(); } if (bb != null) { bb.close(); } } catch (Exception e) { e.printStackTrace(); } }
PrintWriter
//--> Character output stream BufferedReader aa = null; PrintWriter bb = null; try { aa = new BufferedReader(new InputStreamReader(new FileInputStream("e:/ test IO flow .txt"))); bb = new PrintWriter("e:/PrintWriter Line break .txt"); String temp = ""; int i = 1; while ((temp = aa.readLine()) != null) { bb.println(i + temp); // Use PrintWriter Streams do not need to be refreshed , The stream has its own refresh and line feed function i++; } } catch (Exception e) { e.printStackTrace(); }finally { try { if (aa != null) { aa.close(); } if (bb != null) { bb.close(); } } catch (Exception e) { e.printStackTrace(); } }
ByteArrayInputStream
//--> Byte array input stream // establish byte Array , Use String call getBytes() Method creation byte[] aa = "abcdefgh".getBytes(); ByteArrayInputStream bb = null; StringBuilder cc = new StringBuilder(); try { // The construction method of byte array input stream requires a byte Array ,byte Arrays act as data sources bb = new ByteArrayInputStream(aa); int temp = 0; while ((temp = bb.read()) != -1) { //System.out.println((char)temp); cc.append((char) temp); // Read all at once } System.out.println(cc.toString()); // No need to use StringBuilder Object connection , Direct output is best }finally { try { if (bb != null) { bb.close(); } } catch (Exception e) { e.printStackTrace(); } }
ByteArrayOutputStream
//--> Byte array output stream ByteArrayOutputStream aa = null; try { aa = new ByteArrayOutputStream(); aa.write('a'); aa.write('b'); aa.write('c'); byte[] arr = aa.toByteArray(); for (int i = 0; i < arr.length; i++) { System.out.print((char) arr[i]); } }finally { try { if (aa != null) { aa.close(); } } catch (Exception e) { e.printStackTrace(); } }
NIO
Manipulating byte arrays
// Create byte cache , The initial length is 10, Initially, write type array ByteBuffer buffer = ByteBuffer.allocate(10); System.out.println(buffer.position()); System.out.println(buffer.limit()); System.out.println(buffer.capacity()); System.out.println("----------------"); String s = "yang"; // In the data buffer.put(s.getBytes()); System.out.println(buffer.position()); System.out.println(buffer.limit()); System.out.println(buffer.capacity()); // Cache inversion buffer.flip(); // Single read byte b = buffer.get(); System.out.println((char)b); System.out.println(buffer.position()); System.out.println(buffer.limit()); System.out.println(buffer.capacity()); // Since a data has been read , Cannot use array to read , You can use the repeat read method , Reset position To read the status buffer.rewind(); System.out.println(buffer.position()); System.out.println(buffer.limit()); System.out.println(buffer.capacity()); // Create a new array to receive the value of the cache byte[] bytes = new byte[buffer.limit()]; buffer.get(bytes); System.out.println(new String(bytes, 0, bytes.length)); // buffer.clear(); System.out.println(buffer.position()); System.out.println(buffer.limit()); System.out.println(buffer.capacity()); //buffer.put(s.getBytes()); buffer.get(bytes); System.out.println(new String(bytes, 0, bytes.length));
Local Channel passageway
@Test public void liu() throws IOException { // The first way FileInputStream fileInputStream = new FileInputStream("E:/1.png"); FileOutputStream fileOutputStream = new FileOutputStream("E:/2.png"); // Create cache ByteBuffer byteBuffer = ByteBuffer.allocate(1024); FileChannel inChannel = fileInputStream.getChannel(); FileChannel outChannel = fileOutputStream.getChannel(); int read = inChannel.read(byteBuffer); while (read != -1) { byteBuffer.flip(); outChannel.write(byteBuffer); byteBuffer.clear(); read = inChannel.read(byteBuffer); } outChannel.close(); inChannel.close(); // The second way FileChannel input = FileChannel.open(Paths.get("E:/1.png"), StandardOpenOption.READ); FileChannel output = FileChannel.open(Paths.get("E:/4.png"), StandardOpenOption.WRITE, StandardOpenOption.CREATE); // Pass in 1 input.transferTo(0, input.size(), output); // Pass in 2 output.transferFrom(input, 0, input.size()); }
Decentralized write aggregate read
@Test public void fenJu() throws IOException { FileInputStream fileInputStream = new FileInputStream("E:/aa.txt"); FileChannel channel1 = fileInputStream.getChannel(); ByteBuffer allocate1 = ByteBuffer.allocate(10); ByteBuffer allocate2 = ByteBuffer.allocate(1024); ByteBuffer[] byteBuffers = { allocate1, allocate2}; long read = channel1.read(byteBuffers); System.out.println(new String(allocate1.array(), 0, allocate1.limit())); System.out.println(new String(allocate2.array(), 0, allocate2.limit())); allocate1.flip(); allocate2.flip(); FileOutputStream fileOutputStream = new FileOutputStream("E:/cc.txt"); FileChannel channel2 = fileOutputStream.getChannel(); channel2.write(byteBuffers); }
Encoding and decoding
@Test public void bianJie() throws CharacterCodingException { // Output all encoding methods , return Map aggregate SortedMap<String, Charset> stringCharsetSortedMap = Charset.availableCharsets(); Set<Map.Entry<String, Charset>> entries = stringCharsetSortedMap.entrySet(); /*for (Map.Entry en : entries) { System.out.println(en.getKey() + " " + en.getValue()); }*/ // get GBK Encoding mode Charset gbk = Charset.forName("GBK"); // Get encoder CharsetEncoder charsetEncoder = gbk.newEncoder(); // Get decoder CharsetDecoder charsetDecoder = gbk.newDecoder(); // get CharBuffer buffer CharBuffer allocate = CharBuffer.allocate(1024); String string = " Invincible "; allocate.put(string); // With GBK Method to encode buffer data , The output needs to reverse the buffer allocate.flip(); ByteBuffer encode = charsetEncoder.encode(allocate); System.out.println(encode.limit()); /*for (int i = 0; i < 4; i++) { System.out.println(encode.get()); }*/ // With GBK Mode to decode encoded data allocate.flip(); CharBuffer decode = charsetDecoder.decode(encode); System.out.println(decode.toString()); }
NIO Realize data transmission between client and server ( Blocked state )
public class ClientServiceBlocking { @Test public void client() throws IOException { // Get the communication channel between the client and the server SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9999)); // Get the communication channel between the client and the disk FileChannel open = FileChannel.open(Paths.get("E:/1.png"), StandardOpenOption.READ); // Test the second way //open.transferTo(0, open.size(), socketChannel); //NIO Create cache ByteBuffer allocate = ByteBuffer.allocate(1024); int read = open.read(allocate); while (read != -1) { allocate.flip(); socketChannel.write(allocate); allocate.clear(); read = open.read(allocate); } // Close channel open.close(); socketChannel.close(); } @Test public void service() throws IOException { // Create a server-side channel ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); // The server side specifies the port accessed by the client , Binding required serverSocketChannel.bind(new InetSocketAddress(9999)); // The server listens to the client information SocketChannel accept = serverSocketChannel.accept(); // Create a server-side and local disk channel FileChannel open = FileChannel.open(Paths.get("E:/2.png"), StandardOpenOption.WRITE, StandardOpenOption.CREATE); // Create a cache to receive client data ByteBuffer allocate = ByteBuffer.allocate(1024); // The server reads the client data int read = accept.read(allocate); // Infinite loop read while (read != -1) { allocate.flip(); open.write(allocate); allocate.clear(); read = accept.read(allocate); } // Close channel open.close(); accept.close(); serverSocketChannel.close(); } }
NIO Realize data transmission between client and server ( Non blocking state )
public class ClientServiceNonBlocking { @Test public void client() throws IOException { // Create client-side and server-side channels SocketChannel open = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9998)); // Set the client channel to non blocking state *** open.configureBlocking(false); // Create client and disk channels FileChannel open1 = FileChannel.open(Paths.get("E:/1.png"), StandardOpenOption.READ); // Create cache ByteBuffer allocate = ByteBuffer.allocate(1024); int read = open1.read(allocate); while (read != -1) { allocate.flip(); open.write(allocate); allocate.clear(); read = open1.read(allocate); } // Close channel open1.close(); open.close(); } @Test public void service() throws IOException { // Create a server-side channel ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); // Set the server non blocking state serverSocketChannel.configureBlocking(false); // Server side binding listening port number serverSocketChannel.bind(new InetSocketAddress(9998)); // Create selector / multiplexer Selector selector = Selector.open(); // Selector agent listens serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); // Create server and disk channels //FileChannel open = FileChannel.open(Paths.get("E:/3.png"), StandardOpenOption.WRITE, StandardOpenOption.CREATE); // Polling for listening information while (selector.select() > 0) { // Traverse the selector listening information set Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while (iterator.hasNext()) { SelectionKey next = iterator.next(); // Make sure that the crying protector is in the ready state if (next.isAcceptable()) { // The server is connected to the client SocketChannel accept = serverSocketChannel.accept(); // Switch non blocking state accept.configureBlocking(false); // Put the read operation in the selector accept.register(selector, SelectionKey.OP_READ); } else if (next.isReadable()) { // Create read channel SocketChannel channel = (SocketChannel) next.channel(); // Create server and disk channels FileChannel open = FileChannel.open(Paths.get("E:/3.png"), StandardOpenOption.WRITE, StandardOpenOption.CREATE); // Create cache ByteBuffer allocate = ByteBuffer.allocate(1024); // Read client channel information int read = channel.read(allocate); System.out.println(read); while (read != -1) { allocate.flip(); open.write(allocate); allocate.clear(); read = channel.read(allocate); } } } // Turn off the iterator iterator.remove(); } } }
Network programming
InetAddress–InetSocketAddress
System.out.println("===============InetAddress Class simple to use ============================="); // according to InetAddress Class to get the native directly InetAddress object InetAddress aa = InetAddress.getLocalHost(); // Access to the host IP Address System.out.println(" Access to the host IP Address "+aa.getHostAddress()); // Get the hostname System.out.println(" Get the host name "+aa.getHostName()); // Get... According to the domain name InetAddress object InetAddress bb = InetAddress.getByName("www.jd.com"); // obtain IP Address System.out.println("www.jd.com Of IP Address " + bb.getHostAddress()); // Get the hostname System.out.println("www.jd.com The host name "+bb.getHostName()); // according to IP The address for InetAddress object InetAddress cc = InetAddress.getByName("163.23.142.67"); System.out.println(" according to 163.23.142.67 To obtain the IP Address " + cc.getHostAddress()); // When you type IP Address 163.23.142.67 Nonexistence or DNS( Domain name resolution system ) It is not allowed to IP Address and domain name mapping , Unable to get host address ( And IP The address has the same name ) //System.out.println(" according to 163.23.142.67 Obtained hostname " + cc.getHostName()); System.out.println("==============InetSocketAddress Class simple to use ============================="); // according to localhost establish InetSocketAddress Class object InetSocketAddress a = new InetSocketAddress("localhost", 8888); System.out.println(a.getAddress()); System.out.println(a.getHostName()); System.out.println(a.getPort()); // according to 127.0.0.1 establish InetSocketAddress object InetSocketAddress c = new InetSocketAddress("127.0.0.1", 7777); System.out.println(c.getAddress()); System.out.println(c.getHostName()); System.out.println(c.getPort()); // according to IP The address for InetSocketAddress object InetSocketAddress b = new InetSocketAddress("192.168.1.5", 9999); System.out.println(b.getAddress()); System.out.println(b.getHostName()); // Get the port number System.out.println(b.getPort()); // according to InetAddress Object to obtain InetSocketAddress object InetAddress f = InetAddress.getByName("192.168.1.40"); InetSocketAddress d = new InetSocketAddress(f, 6666); System.out.println(d.getAddress()); System.out.println(d.getHostName()); System.out.println(d.getPort());
Reptiles
//URL The method is simple to use // establish URL object URL aa = new URL("https://www.baidu.com"); // Get agreement name System.out.println(" Get agreement name :"+aa.getProtocol()); // Get the hostname System.out.println(" Get the hostname :"+aa.getHost()); // Access to domain name System.out.println(" Access to domain name :"+aa.getPort()); // Get the file name System.out.println(" Get the file name :"+aa.getFile()); // Get the default port number System.out.println(" Get the default port number :"+aa.getDefaultPort()); // Get path System.out.println(" Get path :"+aa.getPath()); // Web crawler // establish URL object URL bb = new URL("https://www.csdn.net/"); //CSDN Website home page // Get byte input stream InputStream cc = bb.openStream(); // Use buffer streams BufferedReader dd = new BufferedReader(new InputStreamReader(cc, "utf-8")); // Store to local disk BufferedWriter ff = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("index.html"), "utf-8")); // Reading while writing String temp = null; while ((temp = dd.readLine()) != null) { ff.write(temp); ff.newLine(); ff.flush(); } dd.close(); ff.close(); cc.close();
The chat room TCP
-- Client multithreading public class Text7{ public static void main(String[] args) throws IOException { System.out.println("==== The client starts !!===="); // establish Socket object Socket aa = new Socket("192.168.1.40", 9999); // Create a thread class object that the client sends information to the server sendMessage bb = new sendMessage(aa); new Thread(bb).start(); // Create a thread class object for the client to receive server information getMessage cc = new getMessage(aa); new Thread(cc).start(); } } // The client sends information to the thread class sendMessage implements Runnable{ DataOutputStream bb = null; BufferedReader cc = null; private Socket aa; private boolean flag = true; // Initialize the incoming through the thread class Socket Endpoint public sendMessage(Socket aa){ this.aa = aa; } // Get keyboard input data private String getMessage(){ // by str initialization , When something goes wrong with the program , You can also return the initialization value String str = ""; try { System.out.println(" Please enter the information sent :"); cc = new BufferedReader(new InputStreamReader(System.in)); str = cc.readLine(); } catch (Exception e) { flag = false; Text9.closeAll(cc); } return str; } // Send data to the server private void sendMessage(String string) { try { bb = new DataOutputStream(aa.getOutputStream()); bb.writeUTF(string); bb.flush(); } catch (IOException e) { flag = false; Text9.closeAll(bb); } } @Override public void run() { while (flag) { this.sendMessage(this.getMessage()); // Sleep is not added here , There is a problem with printing , Because it's dual threaded try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } } // The client receives the information thread class getMessage implements Runnable { DataInputStream oo = null; private Socket bb; private boolean flag = true; public getMessage(Socket socket) { this.bb = socket; } // Get server information private void receiveServerMessage() { try { oo = new DataInputStream(bb.getInputStream()); System.out.println(oo.readUTF()); } catch (Exception e) { flag = false; Text9.closeAll(oo); } } @Override public void run() { while (flag) { this.receiveServerMessage(); } } }-- Server side public class Text8{ public static void main(String[] args) throws IOException { System.out.println("==== Server startup ===="); // establish ServerSocket object ServerSocket aa = new ServerSocket(9999); // Listen for requests from clients Socket bb = aa.accept(); // Data streams get input and output // Data stream get input while (true) { DataInputStream q = new DataInputStream(bb.getInputStream()); //***q.readUTF() When used many times , It is necessary to define variable reception !! String str = q.readUTF(); System.out.println(" The client sends information :"+str); // Data stream get output DataOutputStream w = new DataOutputStream(bb.getOutputStream()); w.writeUTF(" The server has received the message :"+str); w.flush(); } } }
Customer consultation UDP
-- Server side public static void main(String[] args) throws IOException { System.out.println("======= Customer service starts !!=============="); Scanner h = new Scanner(System.in); DatagramSocket aa = new DatagramSocket(9999); while (true) { byte[] arr = new byte[1024]; DatagramPacket bb = new DatagramPacket(arr, arr.length); // Start receiving aa.receive(bb); // View the received data // Don't understand, // I understand String str = new String(bb.getData(), 0, bb.getLength()); System.out.println(" Customer said :" + str); String p = h.next(); byte[] arr2 = p.getBytes(); DatagramPacket cc = new DatagramPacket(arr2, arr2.length, bb.getAddress(), bb.getPort()); aa.send(cc); if ("bye".equals(p)) { break; } } }-- client public static void main(String[] args) throws IOException { Scanner h = new Scanner(System.in); System.out.println("======= The consultant starts !!========="); // Datagram packets for sending and receiving // This application will send data , Use the port unique to this application DatagramSocket aa = new DatagramSocket(8888); while (true) { String p = h.next(); // Ready to send packets byte[] arr = p.getBytes(); // Data sent , Data length , Address sent to the host , Port sent to the host DatagramPacket bb = new DatagramPacket(arr, arr.length, InetAddress.getByName("localhost"), 9999); // Start sending aa.send(bb); // Store received datagram packets byte[] arr2 = new byte[1024]; DatagramPacket cc = new DatagramPacket(arr2, arr2.length); // Receive datagram packets aa.receive(cc); String str = new String(cc.getData(), 0, cc.getLength()); System.out.println(" Customer service said :" + str); if ("bye".equals(p)) { break; } } // Close data //aa.close(); }
边栏推荐
- Neo4j realizes social recommendation (4)
- Paper understanding [RL - exp replay] - an equivalence between loss functions and non uniform sampling in exp replay
- MySQL basic query statement
- How do you view the multi runtime architecture of dapr and layotto?
- Annexe 17 interprétation du programme réseau
- three.js学习笔记(十六)——汹涌的海洋
- Postman interface pressure test
- Do you want to explore MySQL not in indexing?
- Postman 接口压力测试
- Error deleting environment variable path
猜你喜欢

Will testing not be replaced by development?
![Esp32 learning notes [WiFi network] - 01ap & sta](/img/04/de14412d6244ec120c587d98f103aa.png)
Esp32 learning notes [WiFi network] - 01ap & sta

MySQL基础 多表查询

SOFA Weekly | Kusion 开源啦、本周 QA、本周 Contributor

Que pensez - vous des architectures Multi - temps comme DAPR et layotto?

Basic pointer ~ guide you to the introduction pointer

Detailed introduction to MySQL basic data types

Redhat7 cracking (resetting) root password

ERP system, compilation and learning

附十七章 網絡程序解讀限定文章
随机推荐
The return value of JPA lookup byid is optional. The return value does not match orElse
Kusionstack has a sense of open source | it took two years to break the dilemma of "separating lines like mountains"
MySQL基础 数据类型精讲
SSM详解
How do you view the multi runtime architecture of dapr and layotto?
Creation of menu for wechat applet development
2022-2028 global linear LED lighting industry research and trend analysis report
如何看待 Dapr、Layotto 這種多運行時架構?
[redis learning 13] redis builds master-slave cluster, sentinel cluster and partition cluster
Implementation of WTM based on NETCORE framework
HAVE FUN | SOFAArk 源码解析活动
Annexe 17 interprétation du programme réseau
了解图数据库neo4j(二)
LeetCode_单调栈_中等_739. 每日温度
Omit application reduces TS duplicate codes
最小路径和
附十七章 網絡程序解讀限定文章
Project interview questions
Error deleting environment variable path
Postman 接口压力测试