?
UDP2_传一个long类型的数
TestUDPServer.java
class="java">import java.net.*; import java.io.*; public class TestUDPServer { public static void main(String args[]) throws Exception { byte buf[] = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf, buf.length); //UDP的5678端口 DatagramSocket ds = new DatagramSocket(5678); while(true) { ds.receive(dp); //打印字符 //System.out.println(new String(buf,0,dp.getLength())); ByteArrayInputStream bais = new ByteArrayInputStream(buf); DataInputStream dis = new DataInputStream(bais); System.out.println(dis.readLong()); } } }
?
F:\java\socket>javac TestUDPServer.java F:\java\socket>java TestUDPServer 10000
?
?
TestUDPClient.java
import java.net.*; import java.io.*; public class TestUDPClient { public static void main(String args[]) throws Exception { //定义一个long类型的数 long n = 10000L; //字节数组 ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); //将n写入字节数组 dos.writeLong(n); byte[] buf = baos.toByteArray(); System.out.println(buf.length); //byte[] buf = (new String("Hello")).getBytes(); DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress("127.0.0.1", 5678) ); DatagramSocket ds = new DatagramSocket(9999); ds.send(dp); ds.close(); } }
?
f:\java\socket>javac TestUDPClient.java f:\java\socket>java TestUDPClient 8 f:\java\socket>
?
?