java Udp协议简单的通讯

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;



class Xieyi extends Thread{
	
	
	@Override
	 //Udp协议的接受端
	public void run() {
	
		 
			 DatagramSocket datagramSocket = null;
			try {
				datagramSocket = new DatagramSocket(8090);
			} catch (SocketException e) {
				
				e.printStackTrace();
			}  
		  
		  byte[] buf=new byte[1024];
		  DatagramPacket datagramPacket=new DatagramPacket(buf, buf.length);
		  try {
			datagramSocket.receive(datagramPacket);
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		  System.out.println(datagramPacket.getAddress().getHostName()+"\t"+new String(buf));
		  datagramSocket.close();
		  run();
		
	}
	
}
public class Work1 {


	public static void main(String[] args) throws IOException {
	
		 
		Xieyi x=new Xieyi();
		x.start();
		Udpxieyi();
		/*  InetAddress address = InetAddress.getLocalHost();
		  System.out.println("IP地址:"+address.getHostAddress());*/
	}
	//Udp协议的发送端
	public static void Udpxieyi()throws IOException{
		
        DatagramSocket dtaSocket=new DatagramSocket();
        Scanner scanner=new Scanner(System.in);     
        String str=scanner.next();
        SimpleDateFormat ri=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date=new Date();
       ri.format(date);
       str= ri.format(date)+"\n"+str;
        DatagramPacket datagramPacket=new DatagramPacket(str.getBytes(),str.getBytes().length , InetAddress.getByName("192.168.6.255"), 9872);
       System.out.println(InetAddress.getLocalHost());
        dtaSocket.send(datagramPacket);
        dtaSocket.close();
		
		Udpxieyi();
		
	}
	 //Udp协议的接受端
/*public static void Udpxieyi2()throws IOException{
	DatagramSocket datagramSocket=new DatagramSocket(9872);  
	  byte[] buf=new byte[1024];
	  DatagramPacket datagramPacket=new DatagramPacket(buf, buf.length);
	  datagramSocket.receive(datagramPacket);
	  System.out.println(new String(buf));
	  datagramSocket.close();
		
	}*/

}

 

posted @ 2016-12-10 10:35  zerobased  阅读(346)  评论(0编辑  收藏  举报