j'ava网络通信UDP

服务器端

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;


public class UDP_Server {


public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(3000);

System.out.println("等待接受数据.......");
while(true){
byte buf[] =new byte[256];
DatagramPacket packet =new DatagramPacket(buf,buf.length);

socket.receive(packet);
String date=new Date().toString();
buf=date.getBytes();
InetAddress addr= packet.getAddress();
int port = packet.getPort();

packet = new DatagramPacket(buf,buf.length,addr,port);
socket.send(packet);
System.out.println("已接受来自"+addr.toString()+":"+port+"的数据");
}
}
}

客户端程序:

package socketUDP;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;


public class UDP_client {


public static void main(String[] args) throws UnknownHostException, IOException {
   String host="localhost";
   byte mes[]=new byte[256];
   InetAddress addr=InetAddress.getByName(host);
   System.out.println("侦听主机为"+host);
   
   DatagramPacket packet = new DatagramPacket(mes,mes.length,addr,3000);
   DatagramSocket socket= new DatagramSocket();
   
   socket.send(packet);
   packet = new DatagramPacket(mes,mes.length);
   socket.receive(packet);
   
   String date = new String(packet.getData());
   System.out.print("侦听主机"+host+"的当前时间为"+date);
   socket.close();
}
}

你可能感兴趣的:(j'ava网络通信UDP)