23,404
社区成员
发帖
与我相关
我的任务
分享
public class SearchLocalComputer {
private int port = 10001;
public void send() throws UnknownHostException{
DatagramPacket dp = null;
DatagramSocket ds = null;
String str = "is there anyone";
byte[] buf = str.getBytes();
dp = new DatagramPacket(buf, buf.length,InetAddress.getByName("localhost"),port);
try {
ds = new DatagramSocket();
System.out.println("send: ");
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ds.send(dp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void receive(){
DatagramSocket ds = null;
DatagramPacket dp = null;
try {
ds = new DatagramSocket(port);
System.out.println("receive: ");
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int size = 1024;
byte[] buf = new byte[size];
dp = new DatagramPacket(buf, buf.length);
try {
ds.receive(dp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int length = dp.getLength();
String msg = new String(dp.getData(),0,length);
System.out.println(msg);
}
public static void main(String[] args) {
SearchLocalComputer slc = new SearchLocalComputer();
if(args[0].equals("send")){
try {
slc.send();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(args[0].equals("receive")){
slc.receive();
}
}
}
try {
int port = 7777;
InetAddress address = InetAddress.getLocalHost();
DatagramSocket dsocket = new DatagramSocket(port, address);
byte[] buffer = new byte[65000];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
// Now loop forever, waiting to receive packets and printing them.
while (true) {
dsocket.receive(packet);
String longtex=new String(buffer, 0, packet.getLength());
..............