//接收端
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;
public class MyReceive {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
DatagramSocket receive =new DatagramSocket(8088);
DatagramSocket send =new DatagramSocket();
byte []array=new byte[1024];
Scanner scanner =new Scanner(System.in);
while(true){
DatagramPacket packet=new DatagramPacket(array,1024);
receive.receive(packet);
byte[]date=packet.getData();
System.out.println("Receive接收的数据是: "+new String(date,0,packet.getLength()));
String sendString=scanner.next();
System.out.println("Receive发送的数据是: "+sendString);
byte[]sendByte=sendString.getBytes();
DatagramPacket packetSend=new DatagramPacket(sendByte,sendByte.length,InetAddress.getByName("192.168.0.141"),8088);
send.send(packetSend);
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//发送端
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;
public class MySend {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
DatagramSocket send = new DatagramSocket();
DatagramSocket receive = new DatagramSocket();
Scanner scanner =new Scanner(System.in);
byte[]receiveaArray=new byte[1024];
while(true){
String s=scanner.next();
byte[]array=s.getBytes();
DatagramPacket packet = new DatagramPacket(array, array.length, InetAddress.getByName("192.168.0.141"), 8088);
System.out.println("开始发送"+s);
send.send(packet);
DatagramPacket packetreceive=new DatagramPacket(receiveaArray,receiveaArray.length);
receive.receive(packetreceive);
byte[] date=packetreceive.getData();
System.out.println("收到的数据是: "+new String(date,0,packetreceive.getLength()));
//System.out.println("收到的数据是: "+new String(date,0,date.length));
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
block
e.printStackTrace();
}
}
}