Java by API/java.net/DatagramSocket
Версия от 17:43, 31 мая 2010; (обсуждение)
Содержание
DatagramSocket: receive(DatagramPacket packet)
/*
* Output:
*
*/
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class MainClass {
private final static int BUFSIZE = 20;
public static void main(String args[]) {
try {
int port = 80;
DatagramSocket ds = new DatagramSocket(port);
while (true) {
byte buffer[] = new byte[BUFSIZE];
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
ds.receive(dp);
String str = new String(dp.getData());
System.out.println(str);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
DatagramSocket: send(DatagramPacket p)
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import javax.swing.JPanel;
public class MainClass extends JPanel {
public static void main(String[] args) {
try {
String data = "data in UDP";
byte [] buffer = data.getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length,
new InetSocketAddress("localhost", 5002));
DatagramSocket socket = new DatagramSocket(5003);
System.out.println("Sending a packet...");
socket.send(packet);
}catch(IOException e)
{
e.printStackTrace();
}
}
}
new DatagramSocket()
/*
* Output:
*
*/
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class MainClass {
public static void main(String args[]) {
try {
InetAddress ia = InetAddress.getByName("www.jexp.ru");
DatagramSocket ds = new DatagramSocket();
byte buffer[] = "hello".getBytes();
DatagramPacket dp = new DatagramPacket(buffer, buffer.length, ia, 80);
// Send the datagram packet
ds.send(dp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
new DatagramSocket(int port)
/*
* Output:
*
*/
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class MainClass {
private final static int BUFSIZE = 20;
public static void main(String args[]) {
try {
int port = 80;
DatagramSocket ds = new DatagramSocket(port);
while (true) {
byte buffer[] = new byte[BUFSIZE];
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
ds.receive(dp);
String str = new String(dp.getData());
System.out.println(str);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}