//服务器
package class3.apr10.danjiaxin;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
/**
* @author danjiaxin
*
*/
public class UDPA {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
System.out.println("服务器启动");
DatagramSocket ds = new DatagramSocket(1234);
byte[] by = new byte[1024];
DatagramPacket dp = new DatagramPacket(by, by.length, InetAddress.getLocalHost(), 1234);
ds.receive(dp);
by = dp.getData();
String str = new String(by).trim();
System.out.println("服务器接受信息是:"+str);
}
}
/客户端
package class3.apr10.danjiaxin;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
/**
* @author danjiaxin
*
*/
public class UDPB {
public static void main(String[] args) throws Exception {
System.out.println("客户端启动");
DatagramSocket ds = new DatagramSocket();
Scanner input = new Scanner(System.in);
System.out.println("请输入客户信息");
String str = input.nextLine();
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.getBytes().length, InetAddress.getLocalHost(), 1234);
ds.send(dp);
}
}
报错:Exception in thread "main" java.net.SocketException: Socket closed
at java.net.PlainDatagramSocketImpl.receive0(Native Method)
at java.net.PlainDatagramSocketImpl.receive(PlainDatagramSocketImpl.java:136)
at java.net.DatagramSocket.receive(DatagramSocket.java:712)
at class3.apr10.danjiaxin.UDPA.main(UDPA.java:25) |
|