1 package com.yyq; 2 3 import java.io.BufferedReader; 4 import java.io.InputStream; 5 import java.io.InputStreamReader; 6 import java.net.DatagramPacket; 7 import java.net.DatagramSocket; 8 import java.net.InetAddress; 9 import java.net.SocketException; 10 11 /* 12 * 编写一个聊天程序。有收数据的部分,有发送数据的部分,这两部分需要同时执行 13 * 那就需要用到多线程技术。一个线程收,一个线程发。 14 * 因为收和发动作是不一致的,所以 15 */ 16 class Send implements Runnable{ 17 private DatagramSocket ds; 18 public Send(DatagramSocket ds){ 19 this.ds = ds; 20 } 21 public void run(){ 22 try{ 23 BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)); 24 String line = null; 25 while((line = bufr.readLine())!=null){ 26 if("88".equals(line)){ 27 break; 28 } 29 else{ 30 byte[] buf = new byte[1024]; 31 DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getLocalHost(),1237); 32 ds.send(dp); 33 } 34 } 35 } 36 catch(Exception e){ 37 throw new RuntimeException("发送端失败!!"); 38 } 39 } 40 } 41 class Rece implements Runnable{ 42 private DatagramSocket ds; 43 public Rece(DatagramSocket ds){ 44 this.ds = ds; 45 } 46 public void run(){ 47 try{ 48 while(true){ 49 byte[] buf = new byte[1024]; 50 DatagramPacket dp = new DatagramPacket(buf,buf.length); 51 ds.receive(dp); 52 String ip = dp.getAddress().getHostAddress(); 53 String data = new String(dp.getData(),0,dp.getLength()); 54 System.out.println(ip+data); 55 } 56 } 57 catch(Exception e){ 58 throw new RuntimeException("接受端失败!!"); 59 } 60 } 61 } 62 public class ChatDemo { 63 public static void main(String[] args) throws SocketException { 64 DatagramSocket sendSocket = new DatagramSocket(); 65 DatagramSocket receSocket = new DatagramSocket(1237); 66 new Thread(new Rece(sendSocket)).start(); 67 new Thread(new Send(sendSocket)).start(); 68 } 69 }
时间: 2024-11-10 01:09:56