键盘输入:传送
package network.socket;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class DemoSend {
public static void main(String[] args) throws Exception{
Scanner sc=new Scanner(System.in);
DatagramSocket socket=new DatagramSocket();
while(true){
String str=sc.nextLine();
if("quit".equals(str)){
socket.close();
break;
}
DatagramPacket packet=
new DatagramPacket(str.getBytes(),str.getBytes().length, InetAddress.getByName("127.0.0.1"),6666);
socket.send(packet);
}
}
}
接收:
package network.socket;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class DemoReceive {
public static void main(String[] args) throws Exception{
DatagramSocket socket=new DatagramSocket(6666); //创建码头,要指定端口号
DatagramPacket packet=new DatagramPacket(new byte[1024],1024);
while (true) {
socket.receive(packet); //开始接收
byte[] arr = packet.getData(); //获取数据
int len = packet.getLength(); //获取有效字节个数
System.out.println(len);
System.out.println(new String(arr, 0, len));
}
}
}