Socket基础之通过UDP协议传递一个long类型数
本例演示通过UDP协议传递一个long类型数,这是java中socket编程中的基础的基础,但是不要小看,用途却很大,比如在网络游戏中,通过传递long类型的数,来记录位置等。
server:
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);DatagramSocket ds=new DatagramSocket(5678);while(true){ds.receive(dp);ByteArrayInputStream bais=new ByteArrayInputStream(buf);DataInputStream dis=new DataInputStream(bais);System.out.println(dis.readLong());}}}
client:
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();//buf.length是8DatagramPacket dp=new DatagramPacket(buf,buf.length,new InetSocketAddress("127.0.0.1",5678));DatagramSocket ds=new DatagramSocket(9999);ds.send(dp);ds.close();}}
运行结果:
