Java填坑之路 2019-06-25
被意外之事干扰了,累死了,但感觉挺好
这篇笔记还需要进一步优化。
package test; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; public class Demo2_receive { public static void main(String[] args) throws IOException { DatagramSocket socket = new DatagramSocket(6666); //创建码头 DatagramPacket packet = new DatagramPacket(new byte[1024],1024); //创建集装箱rue while(true) { socket.receive(packet);//接货,接收数据 byte[] arr = packet.getData(); int len = packet.getLength(); String ip = packet.getAddress().getHostAddress(); int port = packet.getPort(); System.out.println(ip + ":" + port + ":" + new String(arr,0,len)); } } }
package test; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.Scanner; public class Demo1_send { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); DatagramSocket socket = new DatagramSocket();//创建码头 while(true) { String line = sc.nextLine(); if("quit".equals(line)) { break; } DatagramPacket packet = new DatagramPacket(line.getBytes(),line.getBytes().length,InetAddress.getByName("127.0.0.1"),6666);//创建集装箱,将数据装进去 socket.send(packet);//从码头中将集装箱发出去 } socket.close();//关闭码头(底层是IO流) } }
package test; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Scanner; public class Demo5 { public static void main(String[] args) { new Receive().start(); new Send().start(); } } class Receive extends Thread { public void run(){ try { DatagramSocket socket = new DatagramSocket(6667); DatagramPacket packet = new DatagramPacket(new byte[1024],1024); while(true) { socket.receive(packet); byte[] arr = packet.getData(); int len = packet.getLength(); String ip = packet.getAddress().getHostAddress(); int port = packet.getPort(); System.out.println(ip + ":" + port + ":" + new String(arr,0,len)); } } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class Send extends Thread { public void run() { try { Scanner sc = new Scanner(System.in); DatagramSocket socket = new DatagramSocket(); while(true) { String line = sc.nextLine(); if("quit".equals(line)) { break; } DatagramPacket packet = new DatagramPacket(line.getBytes(),line.getBytes().length,InetAddress.getByName("127.0.0.1"),6667); socket.send(packet); } socket.close(); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
留坑待填
客户端
服务端
留坑待填
留坑待填
留坑待填
留坑待填
叨逼叨两句收拾收拾~18-11:Collection中的常见方法sortpackage com.test.demo001;System.out.println; //根据默认排序结果获取集合中的最大值