import java.net.DatagramPacket; import java.net.DatagramSocket; /** * 接收线程 * * @author xiaoduc * */ public class ReceiveThread extends Thread { private DatagramSocket ds; public ReceiveThread(int port) { super(); try { this.ds = new DatagramSocket(port); } catch (Exception e) { e.printStackTrace(); } } @Override public void run() { try { //创建byte数组 byte[] buff=new byte[1024]; //创建一个数据包对象 DatagramPacket dp=new DatagramPacket(buff, 1024); //永真循环 while(true){ ds.receive(dp);//接收消息 String str=new String(dp.getData(),0,dp.getLength());//得到数据 System.out.println("接收:"+str);//打印消息 } } catch (Exception e) { e.printStackTrace(); }finally { ds.close(); } } }
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; /** * 发送线程类 * @author xiaoduc * */ public class SendThread extends Thread{ private DatagramSocket ds; private int sendPort; public SendThread(int port,int sendPort){ super(); this.sendPort=sendPort; try { this.ds=new DatagramSocket(port); } catch (Exception e) { e.printStackTrace(); } } @Override public void run() { try { //循环接收用户输入 BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str=null; while((str=br.readLine())!=null){ //创建Datagrampacket对象 DatagramPacket dp=new DatagramPacket(str.getBytes(), 0,str.length(),InetAddress.getByName("localhost"),sendPort); ds.send(dp);//发送数据 System.out.println("发送:"+str);//打印 } } catch (Exception e) { e.printStackTrace(); }finally { ds.close(); } } }
public class Chat { public static void main(String[] args) { //启动发送线程 new SendThread(1091, 1099).start(); } }
public class ReceiveChat { public static void main(String[] args) { //启动接收线程 new ReceiveThread(1099).start(); } }