JavaSE------网络编程(IP,TCP,UDP)

1.IP以及端口

public class demo {
    public static void main(String[] args) {
        InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 8080);
        InetSocketAddress socketAddress2 = new InetSocketAddress("localhost", 8089);
        System.out.println(socketAddress);
        System.out.println(socketAddress2);

        System.out.println(socketAddress.getAddress());
        System.out.println(socketAddress.getHostName());
        System.out.println(socketAddress.getPort());

    }
}
/127.0.0.1:8080
localhost/127.0.0.1:8089
/127.0.0.1
127.0.0.1
8080
public class demo2 {
    public static void main(String[] args) throws UnknownHostException {
       /* InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
        System.out.println(inetAddress);*/
        InetAddress inetAddress1 = InetAddress.getByName("localhost");
        System.out.println(inetAddress1);
        InetAddress inetAddress2 = InetAddress.getLocalHost();
        String hostName = inetAddress1.getHostName();
        System.out.println(hostName);
        System.out.println(inetAddress2);

        InetAddress inetAddress3 = InetAddress.getByName("www.baidu.com");
        System.out.println(inetAddress3);

        System.out.println(inetAddress3.getCanonicalHostName());
        System.out.println(inetAddress3.getHostAddress());
        System.out.println(inetAddress3.getHostName());

    }
}
localhost/127.0.0.1
localhost
DESKTOP-Q9AHENK/192.168.1.176
www.baidu.com/14.215.177.38
14.215.177.38
14.215.177.38
www.baidu.com

2 .TCP实现聊天

用户端

public class Clientdemo1 {
    public static void main(String[] args) throws IOException {

        Socket socket=null;
        OutputStream os=null;

        try {
            InetAddress serverIP = InetAddress.getByName("127.0.0.1");
            int port=9999;
            socket = new Socket(serverIP, port);
            os=socket.getOutputStream();
            os.write("欢迎光临".getBytes());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }finally {
            if(os!=null){
                os.close();
            }
        }
    }
}

服务端

public class Serverdemo1 {
    public static void main(String[] args) {
        ServerSocket serverSocket=null;
        Socket socket=null;
        InputStream is=null;
        ByteArrayOutputStream baos=null;

        try {
            serverSocket= new ServerSocket(9999);
            // 这里的while循环并没有生效,需要再考虑考虑
            while(true){
                socket=serverSocket.accept();
                is=socket.getInputStream();

                baos=new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while((len=is.read(buffer))!=-1){
                    baos.write(buffer,0,len);
                }
                System.out.println(baos.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(baos!=null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){
               try {
                  is.close();
               } catch (IOException e) {
                  e.printStackTrace();
               }
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

3.URL实现下载网络资源

public class Download {
    public static void main(String[] args) throws IOException {
        URL url = new URL("输入地址");//输入要下载的地址
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
        InputStream inputStream = urlConnection.getInputStream();

        FileOutputStream fileOutputStream = new FileOutputStream("f.m4a");
        byte[] buffer = new byte[1024];
        int len;
        while((len=inputStream.read())!=-1){
            fileOutputStream.write(buffer);
        }

        fileOutputStream.close();
        inputStream.close();
        urlConnection.connect();
    }
}

4.UDP多线程在线咨询

public class TalkReceive implements Runnable {

    DatagramSocket socket = null;
    private int port;
    private String msgFrom;

    public TalkReceive(int port,String msgFrom) {
        this.port = port;
        this.msgFrom = msgFrom;
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {

        while (true){

            try {
                //准备接收包裹
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container,0,container.length);
                socket.receive(packet); //阻塞式接收包裹

                //断开连接  bye
                byte[] data = packet.getData();
                String receiveData = new String(data, 0, data.length);

                System.out.println(msgFrom +":"+receiveData);

                if (receiveData.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        socket.close();
    }
}

public class TalkSend implements Runnable {
    DatagramSocket socket = null;
    BufferedReader reader = null;

    private int fromPort;
    private String toIP;
    private int toPort;

    public TalkSend(int fromPort, String toIP, int toPort) {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;

        try {
            socket = new DatagramSocket(fromPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public void run() {

        while (true) {
            try {
                String data = reader.readLine();
                byte[] datas = data.getBytes();
                DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress(this.toIP,this.toPort));

                socket.send(packet);
                if (data.equals("bye")){
                    break;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        socket.close();
    }


}


public class TalkStudent {
    public static void main(String[] args) {
        //开启两个线程
        new Thread(new TalkSend(7777,"localhost",9999)).start();
        new Thread(new TalkReceive(8888,"老师")).start();
    }
}

public class TalkTeacher {

    public static void main(String[] args) {
        new Thread(new TalkSend(5555,"localhost",8888)).start();
        new Thread(new TalkReceive(9999,"学生")).start();
    }

}


public class UdpReceiveDemo1 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(6666);

        while (true){


            //准备接收包裹
            byte[] container = new byte[1024];
            DatagramPacket packet = new DatagramPacket(container,0,container.length);
            socket.receive(packet); //阻塞式接收包裹

            //断开连接  bye
            byte[] data = packet.getData();
            String receiveData = new String(data, 0, data.length);

            System.out.println(receiveData);

            if (receiveData.equals("bye")){
                break;
            }


        }

        socket.close();

    }
}

```java

public class UdpSenderDemo1 {
    public static void main(String[] args) throws Exception {

        DatagramSocket socket = new DatagramSocket(8888);

        //准备数据: 控制台读取 System.in
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        while (true) {
            String data = reader.readLine();
            byte[] datas = data.getBytes();
            DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",6666));

            socket.send(packet);
            if (data.equals("bye")){
                break;
            }
        }



        socket.close();
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值