Java 网络编程

1.IP地址

InetAddress类

网络编程的三个要素:IP地址,端口,协议

public String getHostName():返回计算机名称

public String getHostAddress():返回计算机的IP地址

public static InetAddress getByName(String host):根据计算机名称或者IP地址构造InetAddress对象

public class InetAddressDemo {
    public static void main(String[] args) throws UnknownHostException{
//        InetAddress ia = InetAddress.getByName("DESKTOP-LR36517");
        InetAddress ia = InetAddress.getByName("192.168.137.1");    // 作用同上
        String name = ia.getHostName();        // 返回计算机名称
        String ip = ia.getHostAddress();    // 返回计算机的IP地址
        System.out.println(name + "----" + ip);
    }
}

 

2. 端口:正在运行的程序的标识

A 每个网络程序至少会有一个逻辑端口

B 用于表示进程的逻辑地址,不同进程的表示不同

C 有效端口:0-65535,其中0-1024系统使用或者保留端口

 

3. 协议UDP和TCP

UDP:将数据源和目的封装在数据包中,不需要建立连接,每一个数据包的大小控制在64K以内,因为无连接,是不可靠的协议,不需要建立连接,速度快

TCP:建立连接,形成传输数据的通道,在连接中进行大数据量的传输,通过三次握手完成连接,是可靠的协议,必须建立连接,效率稍微降低

 

4. Socket通信

Socket套接字:网络上具有唯一表示的IP地址和端口号组合在一起才能构成唯一能识别的标识符套接字

Socket原理机制:通信的两端都有Socket,网络通信其实就是Socket间的通信,数据在两个Socket之间通过IO传输

 

5. UDP网络数据通信

5.1 UDP协议发送和接收数据

public class ReceiveData {
    public static void main(String[] args) throws IOException{
        DatagramSocket ds = new DatagramSocket(10086);
        byte[] bys = new byte[1024];
        DatagramPacket dp = new DatagramPacket(bys, bys.length);
        ds.receive(dp);
        
        InetAddress address = dp.getAddress();
        String ip = address.getHostAddress();
        /*
         * String ip = dp.getAddress().getHostAddress();
         */
        
        byte[] by = dp.getData();
        int len = dp.getLength();
        String s = new String(by, 0, len);
        System.out.println(ip + ":" + s);
        ds.close();
    }
}

public class SendData {
    public static void main(String[] args) throws IOException{
        DatagramSocket ds = new DatagramSocket();
        
        byte[] bys = "hello.world".getBytes();
        
        int length = bys.length;
        InetAddress address = InetAddress.getByName("192.168.137.1");
        int port = 10086;
        DatagramPacket dp = new DatagramPacket(bys, length, address, port);
        /* 等同于:
         * DatagramPacket dp = new DatagramPacket(bys, bys.length, InetAddress.getByName("192.168.137.1"), 10086);     
        */
        
        
        ds.send(dp);
        ds.close();
    }
}

 改进版本:无限版本,输入close结束

public class SendData {
    public static void main(String[] args) throws IOException{
        DatagramSocket dsSend = new DatagramSocket();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        while((line = br.readLine()) != null){
            if(line.equals("close")){
                break;
            }
            byte[] bys = line.getBytes();
//            DatagramPacket dp = new DatagramPacket(bys, bys.length, InetAddress.getByName("192.168.137.1"), 12345);
            DatagramPacket dp = new DatagramPacket(bys, bys.length, InetAddress.getByName("192.168.137.255"), 12345);    // 255是广播地址
            dsSend.send(dp);
        }
        dsSend.close();
    }
}
public class ReceiveData {
    public static void main(String[] args) throws IOException{
        DatagramSocket ds = new DatagramSocket(12345);
        while(true){
            byte[] byt = new byte[1024];
            DatagramPacket dp = new DatagramPacket(byt, byt.length);
            ds.receive(dp);
            
            String ip = dp.getAddress().getHostAddress();
            String s = new String(dp.getData(), 0, dp.getLength());
            
            System.out.println(ip + ":" + s);
        }
    }
}

 聊天室:

public class SendThread implements Runnable {
    private DatagramSocket dsSend;
    
    public SendThread(DatagramSocket dsSend) {
        super();
        this.dsSend = dsSend;
    }

    public SendThread() {
        super();
        // TODO Auto-generated constructor stub
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        try{
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String line = null;
            while((line = br.readLine()) != null){
                if(line.equals("close")){
                    break;
                }
                byte[] bys = line.getBytes();
//                DatagramPacket dp = new DatagramPacket(bys, bys.length, InetAddress.getByName("192.168.137.1"), 12345);
                DatagramPacket dp = new DatagramPacket(bys, bys.length, InetAddress.getByName("192.168.137.255"), 12345);    // 255是广播地址
                dsSend.send(dp);
            }
            dsSend.close();
        }catch(IOException e){
            e.printStackTrace();
        }
        
    }

}
public class ReceiveThread implements Runnable {
    private DatagramSocket dsReceive;

    public ReceiveThread(DatagramSocket dsReceive) {
        super();
        this.dsReceive = dsReceive;
    }

    public ReceiveThread() {
        super();
        // TODO Auto-generated constructor stub
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        try{
            while(true){
                byte[] byt = new byte[1024];
                DatagramPacket dp = new DatagramPacket(byt, byt.length);
                
                dsReceive.receive(dp);
                
                String ip = dp.getAddress().getHostAddress();
                String s = new String(dp.getData(), 0, dp.getLength());
                
                System.out.println(ip + ":" + s);
            }
        }catch(IOException e){
            e.printStackTrace();
        }
        
    }

}
public class Chat {
    public static void main(String[] args) throws IOException{
        DatagramSocket dsSend = new DatagramSocket();
        DatagramSocket dsReceive = new DatagramSocket(12345);
        
        SendThread st = new SendThread(dsSend);
        ReceiveThread rt = new ReceiveThread(dsReceive);
        
        Thread ts = new Thread(st);
        Thread tr = new Thread(rt);
        
        ts.start();
        tr.start();
    }
}

 

6. TCP协议传输数据

发送数据:

A:创建发送端的Socket对象

B:获取输出流,写数据

C:释放资源

接收数据:

A:创建接收端的Socket对象

B:监听客户端连接,返回一个对应的Socket对象

C:获取输入流,读取数据显示在控制台

D:释放资源

例:TCP协议传送数据

public class Client {
    public static void main(String[] args) throws IOException{
        Socket s = new Socket("192.168.137.1", 12345);
        OutputStream os = s.getOutputStream();
        os.write("hello, tcp".getBytes());
        
        InputStream is = s.getInputStream();
        byte[] bys = new byte[1024];
        int len = is.read(bys);
        String receive = new String(bys, 0, len);
        System.out.println("receive:" + receive);
        
        s.close();
    }
}
public class Server {
    public static void main(String[] args) throws IOException{
        ServerSocket ss =new ServerSocket(12345);
        
        Socket s = ss.accept();        // 监听客户端连接
        
        String ip = s.getInetAddress().getHostAddress();
        
        InputStream is = s.getInputStream();
        byte[] bys = new byte[1024];
        int len = is.read(bys);
        String str = new String(bys, 0, len);
        System.out.println(ip + "----" + str);
        
        OutputStream os = s.getOutputStream();
        os.write("数据已经受到".getBytes());
        
        s.close();
    }
}

客户端键盘录入服务器控制台:

public class Client {
    public static void main(String[] args) throws IOException, IOException{
        Socket s = new Socket("192.168.137.1", 22222);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        String line = null;
        while((line = br.readLine()) != null){
            if(line.equals("close")){
                break;
            }
            bw.write(s.getInetAddress().getHostAddress() + ":" + line);
            bw.newLine();
            bw.flush();
        }
        s.close();
    }
}
public class Server {
    public static void main(String[] args) throws IOException{
        ServerSocket ss = new ServerSocket(22222);
        Socket s = ss.accept();
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String line = null;
        while((line = br.readLine()) != null){
            System.out.println(line);
        }
        s.close();
    }
}

 客户端键盘录入服务器写到文本文件

public class Client {

    public static void main(String[] args) throws IOException, IOException {
        Socket s = new Socket("192.168.137.1", 22222);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        String line = null;
        while((line = br.readLine()) != null){
            bw.write(line);
            bw.newLine();
            bw.flush();
        }
        s.close();
    }

}

public class Server {

    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(22222);
        Socket s = ss.accept();
        
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        BufferedWriter bw = new BufferedWriter(new FileWriter("xiao.txt", true));
        String line = null;
        while((line = br.readLine()) != null){
            bw.write(line);
            bw.newLine();
            bw.flush();
        }
        s.close();
        bw.close();
    }

}

客户端读取文本文件输出到服务器的控制台:

public class Client {
    public static void main(String[] args) throws IOException{
        Socket s = new Socket("192.168.137.1", 23456);
        BufferedReader br = new BufferedReader(new FileReader("copy.java"));
        BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        String line = null;
        while((line = br.readLine()) != null){
            bw.write(line);
            bw.newLine();
            bw.flush();
        }
        br.close();
        s.close();
    }
}
public class Server {
    public static void main(String[] args) throws IOException{
        ServerSocket ss = new ServerSocket(23456);
        Socket s = ss.accept();
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String line = null;
        while((line = br.readLine()) != null){
            System.out.println(line);
        }
    }
}

 客户端读取文本文件输出到服务器的控制台:(增加反馈版)

public class Client {
    public static void main(String[] args) throws IOException{
        Socket s = new Socket("192.168.137.1", 23456);
        BufferedReader br = new BufferedReader(new FileReader("copy.java"));
        BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        String line = null;
        while((line = br.readLine()) != null){
            bw.write(line);
            bw.newLine();
            bw.flush();
        }
        s.shutdownOutput();    // 结束通道流的传输。
        BufferedReader brc = new BufferedReader(new InputStreamReader(s.getInputStream()));
        while((line = brc.readLine()) != null){
            System.out.println(line);
        }
        br.close();
        s.close();
    }
}

public class Server {
    public static void main(String[] args) throws IOException{
        ServerSocket ss = new ServerSocket(23456);
        Socket s = ss.accept();
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String line = null;
        while((line = br.readLine()) != null){
            System.out.println(line);
        }
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        line = "结束啦";
        bw.write(line);
        bw.newLine();
        bw.flush();
        s.close();
    }
}

7. TCP协议传输图片

public class Server {

    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(10086);
        Socket s = ss.accept();
        BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("skdf.jpg"));
        byte[] bys = new byte[1024];
        int len = 0;
        while((len = bis.read(bys)) != -1){
            bos.write(bys, 0, len);
            bos.flush();
        }
        OutputStream os = s.getOutputStream();
        os.write("上传图片成功".getBytes());
        bis.close();
        bos.close();
        ss.close();
        
    }

}

public class Client {
    public static void main(String[] args) throws IOException{
        Socket s = new Socket("192.168.137.1", 10086);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("abc.jpg"));
        BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
        byte[] bys = new byte[1024];
        int len = 0;
        while((len = bis.read(bys)) != -1){
            bos.write(bys, 0, len);
        }
        s.shutdownOutput();
        InputStream is = s.getInputStream();
        byte[] byt = new byte[1024];
        len = is.read(byt);
        String cl = new String(byt, 0, len);
        System.out.println(cl);
        s.close();
        bis.close();
    }
}

 

posted @ 2018-09-09 11:11  风影旋新月  阅读(142)  评论(0编辑  收藏  举报