简单的udp传输程序。
import java.net.*;
import java.io.*;
public class UDPServer {
public static void main(String[] args) throws Exception {
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
DatagramSocket ds = new DatagramSocket(8888);
while(true) {
ds.receive(dp);
System.out.println(new String(buf,0,dp.getLength()));
}
}
}
UDPCilent
import java.net.*;
public class UDPCilent {
public static void main(String[] args) throws Exception {
byte[] buf = (new String(String.valueOf(2365L)).getBytes());
DatagramPacket dp = new DatagramPacket(buf,buf.length,new InetSocketAddress("192.168.1.100",8888));
DatagramSocket ds = new DatagramSocket(6666);
ds.send(dp);
ds.close();
}
}
将一个long型数传输,经常用到,使用了io流的相关知识。
import java.net.*;
import java.io.*;
public class UDPServer {
public static void main(String[] args) throws Exception {
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
DatagramSocket ds = new DatagramSocket(8888);
while(true) {
ds.receive(dp);
ByteArrayInputStream bas = new ByteArrayInputStream(buf);
DataInputStream dis = new DataInputStream(bas);
System.out.println(dis.readLong());
}
}
}
客户端
import java.net.*;
import java.io.*;
public class UDPCilent {
public static void main(String[] args) throws Exception {
long n = 54651L;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeLong(n);
byte[] buf = bos.toByteArray();
System.out.println(buf.length);
DatagramPacket dp = new DatagramPacket(buf,buf.length,new InetSocketAddress("192.168.1.100",8888));
DatagramSocket ds = new DatagramSocket(6666);
ds.send(dp);
ds.close();
}
}