3、UDP聊天实现
System.in返回的是InputStream指向命令行输入的字节流,它的read方法以字节流的方式来读取命令行的输入的数据。
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketAddress; public class UdpSender { public static void main(String[] args) throws Exception { //使用DatagramSocket建立UDP socket DatagramSocket socket = new DatagramSocket(8888); while (true){ //UDP数据报,报文,从控制台读取 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); //调用readline方法,读取输入的行数据 String data = reader.readLine(); //转换为字节 byte[] datas=data.getBytes(); //建立UDP数据报 DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost",6666)); //发送数据 socket.send(packet); //退出判断 if (data.equals("bye")){ break; } } //关闭socket socket.close(); } }
import java.net.DatagramPacket; import java.net.DatagramSocket; public class UdpReciver { public static void main(String[] args) throws Exception { //使用DatagramSocket 建立UDP socket DatagramSocket socket = new DatagramSocket(6666); while (true){ System.out.println("111111111111"); //准备接收报文包 byte[] container=new byte[1024]; //建立udp数据报 DatagramPacket packet = new DatagramPacket(container,0,container.length); //接收UDP数据报 socket.receive(packet); //接收包裹 byte[] data = packet.getData(); String receiveData = new String(data,0,data.length); //打印接收 System.out.println(receiveData); //断开连接 bye if (receiveData.equals("bye")){ break; } //使用socket接收,阻塞式接收包裹 socket.receive(packet); } socket.close(); } }
原创文章,作者:bd101bd101,如若转载,请注明出处:https://blog.ytso.com/273078.html