Java_UDP聊天

来源:互联网 发布:蓝桥杯c语言300试题 编辑:程序博客网 时间:2024/04/29 02:52
import java.io.*;import java.net.*;class UdpSend implements Runnable{private DatagramSocket ds;public UdpSend(DatagramSocket ds){this.ds = ds;}public void run() {try{BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));String line = null;while((line = bufr.readLine())!=null){if("886".equals(line))break;byte [] buf = line.getBytes();DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("10.100.83.188"),10003);ds.send(dp);}}catch(Exception e){throw new RuntimeException("发送失败!!");}}}class UdpRece implements Runnable{private DatagramSocket ds;public UdpRece(DatagramSocket ds){this.ds = ds;}public void run() {try{while(true){byte [] buf = new byte[1024];DatagramPacket dp = new DatagramPacket(buf,buf.length);ds.receive(dp);String ip = dp.getAddress().getHostAddress();String data = new String(dp.getData(),0,dp.getLength());System.out.println(ip+":"+data);}}catch(Exception e){throw new RuntimeException("接收失败!!");}}}public class chatDemo {public static void main(String[] args) throws Exception {DatagramSocket sendSocket = new DatagramSocket();DatagramSocket receSocket = new DatagramSocket(10003);new Thread(new UdpSend(sendSocket)).start();new Thread(new UdpRece(receSocket)).start();}}

0 0