给个例子
*************SERVER 端*******************
package udp;
import java.net.*;
public class UDPServer {
public static void main(String[] args) throws Exception {
DatagramSocket ds=new DatagramSocket(9000);
while(true){
// 做一封空信,等待接收
byte[] bs2=new byte[20];
DatagramPacket dp2=new DatagramPacket(bs2,0,bs2.length);
ds.receive(dp2);
System.out.println(new String("dp2 "+ new String(dp2.getData())));
InetAddress ia=dp2.getAddress();
int port=dp2.getPort();
String str="今天你结婚了吗!";
byte[] bs=str.getBytes();
DatagramPacket dp=new DatagramPacket(bs,0,bs.length,ia,port);
ds.send(dp);
System.out.println(new String(dp.getData()));
}
}
}
************客户端*************************
package udp;
import java.net.*;
public class UDPClient {
public static void main(String[] args) throws Exception {
DatagramSocket ds=new DatagramSocket();
//做一封信,发出去
String str="我一直在等你";
byte[] bs=str.trim().getBytes();
DatagramPacket dp1=new DatagramPacket(bs,0,bs.length,InetAddress.getLocalHost(),9000);
ds.send(dp1);
//做一封空信,等待接收
byte[] bs2=new byte[20];
DatagramPacket dp2=new DatagramPacket(bs2,0,bs2.length);
ds.receive(dp2);
System.out.println(new String(dp2.getData())+"----------");
ds.close();
}
}
什么啊???????
不明白
我也不会
给你顶一个吧
期待高手出现
w我也是刚学,不过你的问题好像是个作业题