Java-网络编程

来源:互联网 发布:ubuntu怎么输入中文 编辑:程序博客网 时间:2024/06/08 15:54

IPDemo

public class IPDemo {    /**     * @param args     * @throws UnknownHostException      * @throws IOException      */    public static void main(String[] args) throws UnknownHostException, IOException {        /*         * ip地址对象。InetAddress         */        //获取本地主机地址对象。//      InetAddress ip = InetAddress.getLocalHost();        //获取其他主机的地址对象。        InetAddress ip = InetAddress.getByName("www.sina.com.cn");        System.out.println(ip.getHostAddress()+":"+ip.getHostName());    }}

UDP协议

UDPSend

public class UDPSend {    /**     * @param args     * @throws IOException      */    public static void main(String[] args) throws IOException {        System.out.println("udp 发送端 run");        /*         * 通过查阅文档,了解到用于UDP传输协议的对象是DatagramSocket。         *          * 通过udp的协议发送一段文本数据。         * 思路:         * 1,需要先建立udp的socket。它具备者发送或者接收功能。         * 2,将数据封装到数据包中。数据包对象是DatagramPacket。         * 3,使用socket对象的send方法将数据包发送出去。         * 4,关闭资源。         *///      1,需要先建立udp的socket。它具备者发送或者接收功能。        DatagramSocket ds = new DatagramSocket(8888);//      2,将数据封装到数据包中。数据包对象是DatagramPacket。        String text = "hello udp来了。";        byte[] buf = text.getBytes();//将数据转成字节数组。//      将字节数组封装到数据包中。        DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.1.255"), 10000);//      3,使用socket对象的send方法将数据包发送出去。        ds.send(dp);//      4,关闭资源。        ds.close();    }}

UDPRece

public class UDPRece {    /**     * @param args     * @throws IOException      */    public static void main(String[] args) throws IOException {        System.out.println("udp 接收端 run");        /*         * 定义一个udp的接收端。接收发送过来的数据。并显示在屏幕上。         * 思路:         * 1,先有udp  socket服务。而且记住:接收端一定要明确端口。否则收不到数据。         * 2,接收数据。之前先将数据存储到数据包中。         * 3,先定义数据包。         * 4,通过数据包对象获取数据包的内容,发送端的ip。发送端的端口,发送过来的数据。         * 5,关闭资源。         *          *///      1,先有udpsocket服务。        DatagramSocket ds = new DatagramSocket(10000);//      2,接收数据。之前先将数据存储到数据包中。//      3,先定义数据包。        byte[] buf = new byte[1024];        DatagramPacket dp = new DatagramPacket(buf, buf.length);        ds.receive(dp);//阻塞//      4,通过数据包对象获取数据包的内容,发送端的ip。发送端的端口,发送过来的数据。        String ip = dp.getAddress().getHostAddress();        int port = dp.getPort();        String text = new String(dp.getData(),0,dp.getLength());        System.out.println(ip+":"+port+":"+text);//      5,关闭资源。        ds.close();    }}

UDPSend2

public class UDPSend2 {    /**     * @param args     * @throws IOException      */    public static void main(String[] args) throws IOException {        System.out.println("udp2 发送端 run");//      1,需要先建立udp的socket。它具备者发送或者接收功能。        DatagramSocket ds = new DatagramSocket(9999);//      2,将数据封装到数据包中。数据包对象是DatagramPacket。数据来自于键盘录入。        BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));        String line = null;        while((line=bufr.readLine())!=null){            if("over".equals(line)){                break;            }            byte[] buf = line.getBytes();//将数据转成字节数组。//          将字节数组封装到数据包中。            DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.1.223"), 10001);//          3,使用socket对象的send方法将数据包发送出去。            ds.send(dp);        }//      4,关闭资源。        ds.close();    }}

UDPRece2

public class UDPRece2 {    /**     * @param args     * @throws IOException     */    public static void main(String[] args) throws IOException {        System.out.println("udp2 接收端 run");        // 1,先有udpsocket服务。        DatagramSocket ds = new DatagramSocket(10001);        while (true) {            // 2,接收数据。之前先将数据存储到数据包中。            // 3,先定义数据包。            byte[] buf = new byte[1024];            DatagramPacket dp = new DatagramPacket(buf, buf.length);            ds.receive(dp);// 阻塞            // 4,通过数据包对象获取数据包的内容,发送端的ip。发送端的端口,发送过来的数据。            String ip = dp.getAddress().getHostAddress();            int port = dp.getPort();            String text = new String(dp.getData(), 0, dp.getLength());            System.out.println(ip + ":" + port + ":" + text);        }        // 5,关闭资源。//      ds.close();    }}

UDPChatTest

public class UDPChatTest {    /**     * @param args     * @throws IOException      */    public static void main(String[] args) throws IOException {        /*         * 案例一:通过udp实现群聊程序。 思路: 这个程序中既有收又有发,需要同时执行,需要使用多线程技术。         * 一个线程负责发,一个线程负责收。需要两个任务。         */        //发送端的socket 接收端的socket        DatagramSocket sendSocket = new DatagramSocket();        DatagramSocket receSocket = new DatagramSocket(10002);        //创建任务对象。        Send send = new Send(sendSocket);        Rece rece = new Rece(receSocket);        //创建线程并开启。        Thread t1 = new Thread(send);        Thread t2 = new Thread(rece);        t1.start();        t2.start();    }}// 发送任务class Send implements Runnable {    private DatagramSocket ds;    public Send(DatagramSocket ds) {        super();        this.ds = ds;    }    @Override    public void run() {        try {            BufferedReader bufr = new BufferedReader(new InputStreamReader(                    System.in));            String line = null;            while ((line = bufr.readLine()) != null) {                byte[] buf = line.getBytes();// 将数据转成字节数组。                DatagramPacket dp = new DatagramPacket(buf, buf.length,                        InetAddress.getByName("192.168.1.223"), 10002);                ds.send(dp);                if ("886".equals(line)) {                    break;                }            }            // 4,关闭资源。            ds.close();        } catch (IOException e) {        }    }}// 接收任务。class Rece implements Runnable {    private DatagramSocket ds;    public Rece(DatagramSocket ds) {        super();        this.ds = ds;    }    @Override    public void run() {        while (true) {            try {                byte[] buf = new byte[1024];                DatagramPacket dp = new DatagramPacket(buf, buf.length);                ds.receive(dp);// 阻塞                String ip = dp.getAddress().getHostAddress();                int port = dp.getPort();                String text = new String(dp.getData(), 0, dp.getLength());                System.out.println(ip + ":" + port + ":" + text);                if(text.equals("886")){                    System.out.println(ip+"....离开聊天室");                }            } catch (IOException e) {            }        }    }}

TCP协议

TCPClient

public class TCPClient {    /**     * @param args     * @throws IOException      * @throws       */    public static void main(String[] args) throws IOException {        System.out.println("客户端运行.......");        /*         * 需求:通过tcp传输将数据发送给服务器。         * 思路:         * 1,建立tcp的客户端socket。明确服务端的地址和端口。         * 2,如果通道建立成功就会出现socket io流。         *      客户端需要做的就获取socket流的中输出流将数据发送目的地服务端。         * 3,通过socket输出流将数据发送。         * 4,关闭资源。         *///      1,建立tcp的客户端socket。明确服务端的地址和端口。        Socket s = new Socket("192.168.1.223",10003);//      2,如果通道建立成功就会出现socket io流。//          客户端需要做的就获取socket流的中输出流将数据发送目的地服务端。        OutputStream out = s.getOutputStream();//      3,通过socket输出流将数据发送。        out.write("hello tcp 来了!".getBytes());//      4,关闭资源。        s.close();    }}

TCPServer

public class TCPServer {    /**     * @param args     * @throws IOException     */    public static void main(String[] args) throws IOException {        System.out.println("服务端开启.....");        /*         * 需求:获取客户端的数据并显示在屏幕上。 思路: 1,创建服务端的socket。明确端口,监听一个端口。         * 2,服务端只要获取到连接过来的客户端就可以和指定的客户端通信了。 3,通过获取客户端的读取流对象读取客户端发来的数据。 4,并显示屏幕上。         */        // 1,创建服务端的socket。明确端口,监听一个端口。        ServerSocket ss = new ServerSocket(10003);        while (true) {            // 2,服务端只要获取到连接过来的客户端就可以和指定的客户端通信了。            Socket s = ss.accept();            String ip = s.getInetAddress().getHostAddress();            System.out.println(ip + ".....connected");            // 3,通过获取客户端的读取流对象读取客户端发来的数据。            InputStream in = s.getInputStream();            // 4,并显示屏幕上。            byte[] buf = new byte[1024];            int len = in.read(buf);            String text = new String(buf, 0, len);            System.out.println(text);            // 5,关闭资源。            s.close();        }        // ss.close();    }}

TCPClient2

public class TCPClient2 {    /**     * @param args     * @throws IOException      * @throws UnknownHostException      */    public static void main(String[] args) throws UnknownHostException, IOException {        /*         * 案例二:实现客户端和服务端的收发过程。         * 客户端         */        System.out.println("客户端2 启动.......");//      创建客户端socket对象。明确服务端地址和端口。        Socket s = new Socket("192.168.1.223", 10004);//      发送数据,通过socket输出流完成。        OutputStream out = s.getOutputStream();        out.write("服务端,我来了".getBytes());//      读取服务端返回的数据,通过socket输入流        InputStream in = s.getInputStream();        byte[] buf = new byte[1024];        int len = in.read(buf);        String text = new String(buf,0,len);        System.out.println(text);//      关闭资源。        s.close();    }}

TCPSever2

public class TCPSever2 {    /**     * @param args     * @throws IOException     */    public static void main(String[] args) throws IOException {        /*         * 案例二:实现客户端和服务端的收发过程。 服务器端。         */        System.out.println("服务端2启动.....");        // 创建tcp服务端socket 明确端口。        ServerSocket ss = new ServerSocket(10004);        while (true) {            // 获取客户端对象。            Socket s = ss.accept();            System.out.println(s.getInetAddress().getHostAddress()                    + ".....connected");            // 读取客户端的发送过来的数据            InputStream in = s.getInputStream();            byte[] buf = new byte[1024];            int len = in.read(buf);            String text = new String(buf, 0, len);            System.out.println(text);            // 给客户端回馈数据。            OutputStream out = s.getOutputStream();            out.write("客户端,我已到收到,哦耶!".getBytes());            // 关闭客户端            s.close();        }        // 关闭服务端。如果不断的获取客户端,不用关闭服务端。//      ss.close();    }}
原创粉丝点击