java 网络编程(三)简单的即时通讯(UDP传输)
发送端:
package cn.sasa.netDemo2; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.Scanner; public class SendDemo { public static void main(String[] args) throws IOException { /** * */ Scanner scanner = new Scanner(System.in); DatagramSocket socket = new DatagramSocket();//发送使用空参构造函数 InetAddress host = InetAddress.getByName("127.0.0.1"); while(true) { String input = scanner.nextLine(); byte[] buff = input.getBytes(); DatagramPacket packet = new DatagramPacket(buff, buff.length, host, 8046); socket.send(packet);//调用send } } }
接收端:
package cn.sasa.netDemo2; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; public class ReceiveDemo { public static void main(String[] args) throws IOException { DatagramSocket socket = new DatagramSocket(8046); byte[] buff = new byte[1024]; while(true) { DatagramPacket packet = new DatagramPacket(buff, buff.length); socket.receive(packet); int length = packet.getLength();//接收的字节长度 System.out.println(new String(buff,0,length)+"==="+packet.getAddress().getHostAddress()); } } }