简单的DatagramSocket demo
- import java.io.IOException;
-
import java.net.DatagramPacket;
-
import java.net.DatagramSocket;
-
-
-
public class UdpRecv {
-
-
public static void main(String[] args) throws IOException{
-
-
DatagramSocket ds = new DatagramSocket(5000);
-
byte[] buf = new byte[1024];
-
DatagramPacket dp = new DatagramPacket(buf,1024);
-
/*
-
* Receives a datagram packet from this socket.
-
* When this method returns, the DatagramPacket's buffer is filled with the data received.
-
* The datagram packet also contains the sender's IP address, and the port number on the sender's machine.
-
* This method blocks until a datagram is received.
-
*/
-
ds.receive(dp);
-
String userinput = new String(dp.getData(),0,dp.getLength());
-
String strRecv = new String(dp.getData(),0,dp.getLength()) + " from "+
-
dp.getAddress().getHostAddress()+":"+dp.getPort();
-
System.out.println(strRecv);
-
ds.close();
-
-
-
}
-
-
}
- import java.io.BufferedReader;
-
import java.io.IOException;
-
import java.io.InputStreamReader;
-
import java.net.DatagramPacket;
-
import java.net.DatagramSocket;
-
import java.net.InetAddress;
-
-
public class UdpSend {
-
-
public static void main(String[] args) throws IOException{
-
while(true){
-
DatagramSocket ds = new DatagramSocket();
-
String str = "hello socket!";
-
BufferedReader userinput = new BufferedReader(new InputStreamReader(System.in));
-
str += userinput.readLine();
-
DatagramPacket dp = new DatagramPacket(str.getBytes(),str.length(),
-
InetAddress.getByName("127.0.0.1"),5000);
-
-
ds.send(dp);
-
ds.close();
-
}
-
-
-
}
-
}
阅读(847) | 评论(0) | 转发(0) |