A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© guohaichang 中级黑马   /  2015-6-19 23:17  /  349 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

UDP通信
多线程随时收发

import java.net.*;
import java.io.*;


class Ssend implements Runnable{
    private DatagramSocket ds;
    private int port;
    public Ssend(DatagramSocket ds,int port) {
        this.ds = ds;
        this.port = port;
    }

    public void run() {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String line = null;
            while((line = br.readLine()) != null ) {
                if("886".equals(line))
                    break;
                byte buf[] = line.getBytes();
                DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("Lenovo_GHC"),port);
                ds.send(dp);
            }
        } catch(Exception e) {

        }
    }
}

class Sreceive implements Runnable{
    private DatagramSocket ds;
    public Sreceive(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) {

        }
    }

}

public class UDP {
    public static void main(String args[]) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("请输入发送目标端口:");
        int sport = Integer.parseInt(br.readLine());
        System.out.print("请输入本程序端口:");
        int rport = Integer.parseInt(br.readLine());

        new Thread(new Ssend(new DatagramSocket(),sport)).start();
        new Thread(new Sreceive(new DatagramSocket(rport))).start();
    }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马