網絡編程

這篇來聊聊網絡編程中的一些操作

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(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();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章