Java总结网络编程

  1. 物理层:主要定义物理设备标准,如网线的接口类型、光纤的接口类型、各种传输介质的传输速率等。它的主要作用是传输比特流(就是由 1、0 转化为电流强弱来进行传输,到达目的地后再转化为 1、0,也就是我们常说的数模转换与模数转换)。这一层的数据叫做比特。
  2. 数据链路层:主要将从物理层接收的数据进行 MAC 地址(网卡的地址)的封装与解封装。常把这一层的数据叫做帧。在这一层工作的设备是交换机, 数据通过交换机来传输。
  3. 网络层:主要将下层接收到的数据进行 IP 地址(例,192.168.0.1)的封装与解封装。在这一层工作的设备是路由器,常把这一层的数据叫做数据包。
  4. 传输层:定义了一些传输数据的协议和端口号(WWW 端口号 80 等),如:TCP(传输控制协议,传输效率低,可靠性强,用于传输可靠性要求高, 数据量大的数据),UDP(用户数据报协议,与 TCP 特性恰恰相反,用于传输可靠性要求不高,数据量小的数据,如 QQ 聊天数据就是通过这种方式传输的)。主要是将从下层接收的数据进行分段和传输,到达目的地址后再进行重组。常常把这一层叫做段。
  5. 会话层:通过传输层(端口号:传输端口与接收端口)建立数据传输的通路。 主要在你的系统之间发起会话或者接收会话请求(设备之间需要互相认识可以是 IP 也可以是 MAC 或者是主机名)。
  6. 表示层:主要是进行对接收的数据进行解释,加密与解密、压缩与解压缩等 (也就是把计算机能够识别的东西转换成人能够识别的东西 (如图片、 声音等) 。
  7. 应用层:主要是一些终端的应用,比如说 FTP(各种文件下载)、WEB(IE 浏览)、QQ 之类的(可以把它理解成我们在电脑屏幕上可以看到的东西,就是终端应用)。P.S.1、每个网卡的 MAC 地址都是全球唯一的。2、路由器实现将数据包发送到指定的地点。3、应用软件之间通信的过程就是层与层之间封包、解封包的过程。
    8.防火墙,功能就是将发送到某程序端口的数据屏蔽掉以及将从该程序端口发出的数据也屏蔽掉。
    9.传输协议:通信的规则。常见协议有UDP,TCP。
    10.UDP:将数据及源和目的封装成数据包,不需要建立连接。每个数据包的大小限制在64K内,无连接,不可靠,但因为无连接,速度快。
    11.TCP:建立连接,形成传输数据的通道,在连接中进行大量的数据传输,通过三次握手完成连接,是可靠协议,因为建立连接,效率会稍低。如:FTP,File Transfer Protocol文件传输协议。
    12.IP地址,InetAddress。PS:InetAddress类的static InetAddress[] getAllByName(String host),此方法是在给定主机名的情况下,根据系统上配置的名称服务器返回其IP地址所组成的数据数组,这是由于有些主机名对应的IP地址不唯一,如新浪,百度都是服务器集群。
public class WebDemo {
    public static void main(String[] args) 
        throws UnknownHostException {
        InetAddress ip = InetAddress.getLocalHost();
        System.out.println(ip);
        ip = InetAddress.getByName("-YongBao");
        System.out.println(ip.getHostName()
                +"-----"+ip.getHostAddress());
        //byte[] ips = null;
        //ips = "127.0.0.1".getBytes();
        //ip = InetAddress.getByAddress(ips);
        //System.out.println(ip.getHostName()+"-----"+ip.getHostAddress());
        System.out.println("--------------------------------------");
        ip = InetAddress.getByName("www.baidu.com");
        System.out.println(ip.getHostName()+"-----"+ip.getHostAddress());
    }
}

13.域名解析先走本地hosts(C:\WINDOWS\system32\drivers\etc\hosts)文件,解析失败,才去访问DNS服务器解析,获取IP地址。通过hosts文件可以屏蔽游戏网站内容弹出。
14.协议:Socket:为网络服务提供的一种机制,通信的两端都有Socket,网络通信其实就是Socket间通信,数据在两个Socket间通过IO传输。
15.UDP传输:DatagramSocket(用来发送和接受数据报包的套接字)与DatagramPacket(数据报包)。建立发送端,接收端,建立数据包,调用Socket的发送接受方法,关闭Socket。发送端与接收端是两个独立的运行程序。

public class UDPSendDemo {
    public static void main(String[] args) throws Exception {
        System.out.println("发送端启动");
        // UDP Socket服务,使用DatagramSocket
        DatagramSocket ds = new DatagramSocket(8888);
        // 封装将要发送的数据
        String str = "udp....DatagramSocket....来了";
        byte[] buf = str.getBytes();
        DatagramPacket dp = new DatagramPacket(buf, buf.length,
                InetAddress.getByName("localhost"), 10000);
        //通过udp的socket服务将数据包发送出去
        ds.send(dp);
        ds.close();
    }
}
public class UDPReceDemo {
    public static void main(String[] args) throws Exception{
        System.out.println("UDP.....datagram...receive");
        //建立UDP服务
        DatagramSocket ds = new DatagramSocket(10000);
        //数据接收包
        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 str = new String(dp.getData(),0,dp.getLength());
        System.out.println("IP="+IP+"\t"+"port="+port+"\t"+"数据:"+str);
        //关闭资源
        ds.close();
    }
}

16.对聊:

public class UDPSendDemo {
    public static void main(String[] args) throws Exception {
        DatagramSocket ds = new DatagramSocket(10000);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        byte[] buf = null;
        DatagramPacket dp = null;
        int len = 0;
        while ((line = br.readLine()) != null) {
            buf = line.getBytes();
            dp = new DatagramPacket(buf, buf.length,
                    InetAddress.getByName("127.0.0.1"), 10001);
            ds.send(dp);
            if(line.equals("886"))
                break;
        }
        br.close();
        ds.close();
    }
}
public class UDPReceDemo{
    public static void main(String[] args) throws Exception{
        DatagramSocket ds = new DatagramSocket(10001);
        byte[] buf = new byte[1024];
        DatagramPacket dp = new DatagramPacket(buf, buf.length);
        while(true){
            ds.receive(dp);
            String IP = dp.getAddress().getHostAddress();
            int port = dp.getPort();
            String str = new String(dp.getData(), 0, dp.getLength());
            System.out.println("IP=" + IP + "\t" + "port=" + port + "\t"
                    + "数据:" + str);
            if(str.equals("886"))
                break;
        }
        ds.close();
    }
}

17.单窗口,群聊:

public class UDPSendThread implements Runnable {
    private DatagramSocket ds;
    private byte[] buf;
    private DatagramPacket dp;
    private BufferedReader br;

    public UDPSendThread() throws Exception {
        ds = new DatagramSocket();
        br = new BufferedReader(new InputStreamReader(System.in));
    }
    @Override
    public void run() {
        String line = null;
        try {
            while ((line = br.readLine()) != null) {
                buf = line.getBytes();
                dp = new DatagramPacket(buf, buf.length,
                        InetAddress.getByName("localhost"), 10001);
                ds.send(dp);
                if (line.equals("886"))
                    break;
            }
            br.close();
            ds.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
public class UDPReceThread implements Runnable {
    private DatagramSocket ds;
    private DatagramPacket dp;
    private byte[] buf;

    public UDPReceThread() throws Exception {
        ds = new DatagramSocket(10001);
        buf = new byte[1024];
    }

    @Override
    public void run() {
        try {
            while (true) {
                dp = new DatagramPacket(buf, buf.length);

                ds.receive(dp);
                String IP = dp.getAddress().getHostAddress();
                int port = dp.getPort();
                String str = new String(dp.getData(), 0, dp.getLength());
                System.out.println("来自" + IP + "---" + port + "说:" + "数据:"
                        + str + "\n");
                if (str.equals("886")) {
                    System.out.println("那个" + IP + "---" + port + "已经退出");
                    break;
                }
            }
            ds.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
public class ShowDemo {
    public static void main(String[] args) throws Exception{
        new Thread(new UDPSendThread()).start();
        new Thread(new UDPReceThread()).start();
    }
}

18.客户端(Client)首先与服务端(Server)建立连接,形成通道(其实就是IO流),然后,数据就可以在通道之间进行传输,并且单个Server端可以同时与多个Client端建立连接。Socket和ServerSocket,建立客户端和服务端,建立连接后,通过Socket中的IO流进行数据的传输,关闭Socket,同样,客户端与服务端是两个独立的应用程序。
19.TCP客户端:客户端需要明确服务器的IP地址以及端口,这样才可以试着去建立连接,如果连接失败,则报异常。连接成功,说明客户端与服务器建立了通道,那么通过IO流就可以进行数据的传输,而Socket对象已经提供了输入流和输出流,通过getInputStream,getOutputStream获取即可。与服务器通讯结束后,关闭Socket。
20.TCP服务端:服务端需要明确它要处理的数据是从哪个端口进入的,当有客户端访问时,要明确是哪个客户端,可通过accept()获取已连接的客户端对象,并通过该对象与客户端利用IO流进行数据传输。当该客户端访问结束,关闭客户端。
21.C-S:示例:

public class ClientDemo {
    public static void main(String[] args) throws Exception{
        //创建客户端Socket服务
        Socket s = new Socket(InetAddress.getByName("Localhost"), 8001);
        //获取Socket流中的输出流
        OutputStream out = s.getOutputStream();
        //使用输出流将指定数据输出去
        out.write("大雄与哆啦A梦的梦想".getBytes());
        //断开连接 关闭资源
        out.close();
        s.close();
    }
}
public class ServerDemo {
    public static void main(String[] args) throws Exception{
        //创建服务端对象
        ServerSocket ss = new ServerSocket(8001);
        //阻塞式
        Socket s = ss.accept();
        String IP = s.getInetAddress().getHostAddress();
        //通过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(IP+"---"+text);
        s.close();
        ss.close();
    }
}

22.TCP协议——客户端与服务端交互:

public class ClientDemo {
    public static void main(String[] args) throws Exception{
        //创建客户端Socket服务
        Socket s = new Socket(InetAddress.getByName("Localhost"), 8001);
        //获取Socket流中的输出流
        OutputStream out = s.getOutputStream();
        //使用输出流将指定数据输出去
        out.write("大雄与哆啦A梦的梦想".getBytes());
        //收回回复
        InputStream in = s.getInputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        len = in.read(buf);
        System.out.println("服务器回复:"+new String(buf,0,len));
        //断开连接 关闭资源
        out.close();
        in.close();
        s.close();
    }
}
public class ServerDemo {
    public static void main(String[] args) throws Exception{
        //创建服务端对象
        ServerSocket ss = new ServerSocket(8001);
        //阻塞式
        Socket s = ss.accept();
        String IP = s.getInetAddress().getHostAddress();
        //通过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(IP+"---"+text);
        //回复
        OutputStream out = s.getOutputStream();
        out.write("服务器收到".getBytes());
        out.close();
        s.close();
        ss.close();
    }
}

23.文本转换TCP客户端和服务端:

public class ClientDemo {
    public static void main(String[] args) throws Exception {
        Socket s = new Socket(InetAddress.getByName("localhost"), 8005);
        // 读取键盘
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        // 读取服务器
        BufferedReader brS = new BufferedReader(new InputStreamReader(
                s.getInputStream()));
        //写到控制端
        PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
        String line = null;
        while((line = br.readLine())!=null){
            if(line.equals("886"))
                break;
            pw.println(line);
            String receStr = brS.readLine();
            System.out.println(receStr);
        }
        br.close();
        brS.close();
        s.close();
    }
}
public class ServerDemo {
    public static void main(String[] args) throws Exception {
        // 创建服务端对象
        ServerSocket ss = new ServerSocket(8005);
        // 阻塞式
        Socket s = ss.accept();
        String IP = s.getInetAddress().getHostAddress();
        // 读取客户端
        BufferedReader br = new BufferedReader(new InputStreamReader(
                s.getInputStream()));
        //获取Socket输出流
        PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
        String line = null;
        while((line = br.readLine())!=null){
            System.out.println(line);
            pw.println(line.toUpperCase());
        }
        pw.close();
        br.close();
        s.close();
        ss.close();
    }
}

24.如上程序在客户端结束之后,服务端也随之结束,原因是:客户端的Socket关闭之后,服务端获取的客户端的Socket读取流也关闭了,因此读取不到数据,满足while的循环结束条件,执行之后的服务关闭方法,所以ServerSocket也就随之关闭了。
25.如上程序的PrintWriter类在打印输出的时候一定要刷新,否则服务器就获取不到数据,如果使用了write方法就会产生这样的现象,刷新可以通过flush方法来执行,而由于获取数据的方法时BufferedReader的readLine方法,只有在遇到”\r\n”标记时才会结束,所以使用PrintWriter的flush方法刷新数据时一定要追加”\r\n”。
26.TCP协议上传文本文件:

public class Client {
    public static void main(String[] args) throws Exception {
        Socket s = new Socket(InetAddress.getByName("localhost"), 10001);
        // 读取本地上传文件
        BufferedReader br = new BufferedReader(new InputStreamReader(
                new FileInputStream("client.txt")));
        String line = null;
        PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
        while ((line = br.readLine()) != null) {
            pw.println(line);
        }
        s.shutdownOutput();
        // 读取回复
        BufferedReader br2 = new BufferedReader(new InputStreamReader(
                s.getInputStream()));
        line = br2.readLine();
        System.out.println(line);
        br.close();
        pw.close();
        s.close();
    }
}
public class Server {
    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(10001);
        Socket s = ss.accept();
        // 写到文件
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream("g:\\server.txt")));
        //读取管道
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String line = null;
        while((line = br.readLine())!= null){
            bw.write(line);
            bw.newLine();
            bw.flush();
        }
        PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
        pw.println("上传完毕");
        pw.close();
        br.close();
        s.close();
        ss.close();
    }
}

27.常见的客户端:IE/chrome 常见的服务器:Tomcat。世界之窗作为客户端,自定义服务器发送信息。示例:

public class MyServer {
    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(10001);
        Socket s = ss.accept();
        String IP = s.getInetAddress().getHostAddress();
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String line = null;
        line = br.readLine();
        System.out.println(line);
        PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
        pw.println("MyTomcat.....send");
        pw.close();
        br.close();
        s.close();
        ss.close();
    }
}

28.发送的请求是:GET / HTTP/1.1 请求行,请求方式:GET;请求的资源路径:/;HTTP协议版本:1.1。(请求消息头,属性名:属性值)HTTP是一个客户端和服务端请求和应答的标准,客户端按照HTTP的标准发送数据到服务器,服务器按照HTTP的标准解析收到的数据。
29. 模拟浏览器:

public class MyClient {
    public static void main(String[] args) throws Exception {
        Socket s = new Socket(InetAddress.getByName("localhost"), 10001);
        PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
        pw.println("GET g:/1.html HTTP/1.1");
        pw.println("Accept: */*");
        pw.println("Host: 127.0.0.1:8080");
        pw.println("Connection: close");
        pw.println();
        pw.println();
        InputStream in = s.getInputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        len = in.read(buf);
        String line = new String(buf, 0, len);
        System.out.println(line);
    }
}

30.URL&URLConnection:URI,同意资源表示符,URL,统一资源定位符,根据URL能够定位到网络的某个资源,是指向互联网的指针。每个URL都是URI,但不是每个URI都是URL,因为URI还有一个子类,即统一资源名称,URN,它命名资源但不指定如何定位资源。示例:

        String str_url = "http://192.168.1.100:8080/myweb/1.html?name=lisi";
        URL url = new URL(str_url);
        System.out.println("getProtocol:" + url.getProtocol());
        System.out.println("getHost:" + url.getHost());
        System.out.println("getPort:" + url.getPort());
        System.out.println("getFile:" + url.getFile());
        System.out.println("getPath:" + url.getPath());
        System.out.println("getQuery:" + url.getQuery());
        InputStream in = url.openStream();// 相 当 于
        url.openConnection().getInputStream();
        byte[] buf = new byte[1024];
        int len = in.read(buf);
        String text = new String(buf, 0, len);
        System.out.println(text);

31.常见的网络结构:C/S client/Server 客户端/服务器模式 特点:客户端和服务器都要编写。开发成本高,维护麻烦。相应的,客户端在本地可以分担一部分任务。B/S browser/Server 浏览器/服务器模式,只需要开发服务器端,不需要开发客户端,由浏览器取代客户端。开发成本相对低,维护简单。但是所有运算都在服务器端完成。
32.TCP协议上传图片,B/S架构。

public class MyServer {
    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(10001);
        Socket s = ss.accept();
        InputStream in = s.getInputStream();
        FileOutputStream fos = new FileOutputStream("g:\\111.bmp");
        byte[] buf = new byte[1024];
        int len = 0;
        while((len = in.read(buf))!=-1){
            fos.write(buf,0,len);
        }
        OutputStream out = s.getOutputStream();
        out.write("上传成功".getBytes());
        s.close();
        ss.close();
    }
}
public class MyClient {
    public static void main(String[] args) throws Exception {
        Socket s = new Socket(InetAddress.getByName("localhost"), 10001);
        File file = new File("g://1.jpg");
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                file));
        byte[] buf = new byte[1024 * 1024];
        int len = 0;
        OutputStream os = s.getOutputStream();
        while ((len = bis.read(buf)) != -1) {
            os.write(buf, 0, len);
        }
        s.shutdownOutput();
        InputStream is = s.getInputStream();
        byte[] buf2 = new byte[1024];
        int length = 0;
        length = is.read(buf2);
        System.out.println(new String(buf2,0,length));
        s.close();
    }
}

33.TCP协议服务端多线程技术:

public class ServerThreadDemo implements Runnable {
    // 通道
    private Socket s;
    // 缓冲
    byte[] buf;
    //
    private static int count = 0;

    public ServerThreadDemo(Socket s) {
        this.s = s;
        buf = new byte[1024];
    }

    @Override
    public void run() {
        count++;
        try {
            // 存储
            BufferedOutputStream bs = new BufferedOutputStream(
                    new FileOutputStream(count + ".part"));
            // 读取
            InputStream in = s.getInputStream();
            // 回馈
            OutputStream out = s.getOutputStream();
            int len = 0;
            while ((len = in.read(buf)) != -1) {
                bs.write(buf, 0, len);
                bs.flush();
            }
            out.write("上传成功!".getBytes());
            bs.close();
            in.close();
            s.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    public static void main(String[] args) throws Exception{
        ServerSocket ss = new ServerSocket(10001);
        while(true){
            Socket s = ss.accept();
            new Thread(new ServerThreadDemo(s)).start();
        }
    }
}

—————————-网络编程————————

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值