最简单的UDP编程

接收端:

import java.io.*;
import java.net.*;

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 bis = new ByteArrayInputStream(buf);
			DataInputStream dis = new DataInputStream(bis);
			System.out.println(dis.readLong());
		}
	}
}

  

发送端:

import java.io.*;
import java.net.*;

public class TestUDPClient{
	public static void main(String[] args) throws Exception{
		
		long n = 10000L;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(bos);
		dos.writeLong(n);
		
		byte[] buf = bos.toByteArray();
		DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress("127.0.0.1", 5678));
		DatagramSocket ds = new DatagramSocket(9999);
		ds.send(dp);
		ds.close();
	}
}

 

 

你可能感兴趣的:(java,编程,.net,dos)