?
UDP1测试代码:
TestUDPServer.java
class="java" name="code">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 Hello
?
TestUDPClient.java
import java.net.*; import java.io.*; public class TestUDPClient { public static void main(String args[]) throws Exception { /* long n = 10000L; ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); dos.writeLong(n); byte[] buf = baos.toByteArray(); ystem.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 f:\java\socket>
?
?
?