java学习【知识点及代码18】

来源:互联网 发布:焦点堆叠软件 编辑:程序博客网 时间:2024/06/05 10:52

一:网络编程三要素+UDP协议讲解
1.1
1.网络通信介绍
2.tcp/ip
3.udp/ip

1.2
Socket通信
网络编程三要素:

ip:    一个计算的标示(找到这个计算机)端口:    应用程序都会对应一个端口,用来进行通信,有效端口:0~65535,其中0~1024系统使用或保留端口(360查看端口)。协议:    总共有2种协议(TCP,UDP)举例说明:    1.找到刘诗诗(ip)    2.对着刘诗诗的而耳朵说话(端口)    3.协议

1.3
三要素详解:
特殊的IP地址:

127.0.0.1   本地回环地址  用来做一些本地测试   ping    IP地址     用来检测本机是否可以和指定的IP地址的计算机可以进行正常通讯ipconfig             用来查看IP地址xxx.xxx.xxx.255 广播地址

端口号:

物理端口        物理设备对应的端口, 网卡口逻辑端口        用来标示我们的计算机上的进程,端口号的有效范围应该是 0-65535,其中0-1024被系统占用或者保留

协议:

UDP    把数据打成一个数据包 , 不需要建立连接    数据包的大小有限制不能超过64k    因为无连接,所以属于不可靠协议(可能丢失数据)    因为无连接 ,所以效率高    TCP    需要建立连接,形成连接通道    数据可以使用连接通道直接进行传输,无大小限制    因为有链接,所以属于可靠协议    因为有链接,所以效率低 

1.4 (InetAddress)
InetAddress:IP地址的描述类

A:InetAddress类的概述    为了方便我们对IP地址的获取和操作,java提供了一个类InetAddress 供我们使用    此类表示互联网协议 (IP) 地址。 B:InetAddress类的常见功能    public static InetAddress getByName(String host)( host: 可以是主机名,也可以是IP地址的字符串表现形式)    public String getHostAddress()返回 IP 地址字符串(以文本表现形式)。    public String getHostName()获取此 IP 地址的主机名。 C:案例演示: InetAddress类的常见功能
package com.edu_01;import java.net.InetAddress;import java.net.UnknownHostException;public class InetAddressDemo {    public static void main(String[] args) throws Exception {        //通过主机ip获取InetAddress对象        InetAddress address = InetAddress.getByName("192.168.20.25");        //public String getHostAddress()返回 IP 地址字符串(以文本表现形式)。        System.out.println(address.getHostAddress());        //public String getHostName()获取此 IP 地址的主机名。         System.out.println(address.getHostName());    }}

1.5(也叫socket编程,套接字编程,网络编程,叫法不一样都是一个东西)
Socket套接字:(利用qq聊天的案例画图进行讲解)
这里写图片描述
网络上具有唯一标识的IP地址和端口号组合在一起才能构成唯一能识别的标识符套接字。

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

1.6
分协议进行讲解网络编程

UDP协议:(写一个标准demo)特点:1.把数据打包2.不需要建立连接,也称为面向无连接协议3.数据需打包,数据大小有限制64k4.无需建立连接,所以不可靠5.速度快

UDP通信步骤:
发送端步骤:

UDP发送数据的步骤:A:创建UDP发送数据端Socket对象B:创建数据包,并给出数据,把数据打包C:通过Socket对象发送数据包 D:释放资源
package com.edu_02;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.SocketException;public class UdpClient {    public static void main(String[] args) throws Exception {        //1.创建udp协议发送端的socket对象        //public DatagramSocket() throws SocketException        DatagramSocket ds = new DatagramSocket();        byte[] buf = "hello".getBytes();        int length = buf.length;        InetAddress address = InetAddress.getByName("192.168.20.254");        int port = 8888;        //2.创建数据包        //public DatagramPacket(byte[] buf, int length,InetAddress address,int port)        DatagramPacket dp = new DatagramPacket(buf, length, address, port);        /**         * 1.你要发送的数据         * 2.发送的数据的长度         * 3.你要发送给的电脑ip         * 4.端口         */        //发送数据        ds.send(dp);        //释放资源        ds.close();         }}

接收端步骤:

UDP协议接收数据步骤:A:创建UDP接收数据端Socket对象B:创建一个接收数据的数据包C:接收数据,数据在数据包中D:解析数据包,并把数据显示在控制台E:释放资源
package com.edu_02;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.SocketException;public class UdpServer {    public static void main(String[] args) throws Exception {        //创建接收端的socket对象        DatagramSocket ds = new DatagramSocket(8888);        //创建一个数据包,用来接收来自发送端的数据,是一个空的数据包        byte[] buf = new byte[1024];        int length = buf.length;        DatagramPacket dp = new DatagramPacket(buf, length);        //接受来自发送端的数据        //public void receive(DatagramPacket p)throws IOException        //程序在这里接收到来自发送端的数据之前一直处于阻塞状态        ds.receive(dp);        //解析一下数据包中的数据        //public byte[] getData()返回数据缓冲区        byte[] data = dp.getData();        //public int getLength()返回将要发送或接收到的数据的长度        int len = dp.getLength();        System.out.println(new String(data,0,len));        //释放资源        ds.close();         }}

1.7 画图讲解udp协议发送和接受数据图解
这里写图片描述
1.8 键盘录入数据实现数据的动态发送

package com.edu_03;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.SocketException;import java.util.Scanner;public class UdpClient {    public static void main(String[] args) throws Exception {        //1.创建发送端的socket对象        DatagramSocket ds = new DatagramSocket();        InetAddress address = InetAddress.getByName("192.168.20.254");        int port = 9999;        //2.创建键盘录入对象        Scanner sc = new Scanner(System.in);        String line;        while ((line=sc.nextLine())!=null) {            //键盘录入的数据line            byte[] buf = line.getBytes();            int length = buf.length;            DatagramPacket dp = new DatagramPacket(buf, length, address, port);            //发送数据包            ds.send(dp);        }        //释放资源        ds.close();         }}
package com.edu_03;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.SocketException;public class UdpServer {    public static void main(String[] args) throws Exception {        //创建接收端的socket对象        DatagramSocket ds = new DatagramSocket(9999);        //接受来自客户端的数据        while (true) {            //创建数据包            byte[] buf = new byte[1024];            int length = buf.length;            DatagramPacket dp = new DatagramPacket(buf, length);            //接受来自客户端的数据            ds.receive(dp);            //解析数据包中的数据            byte[] data = dp.getData();            int len = dp.getLength();            System.out.println(new String(data, 0, len));        }           }}

1.9 dos命令行演示聊天室(多个窗口实现群聊)

package com.edu_04;import java.net.DatagramSocket;import java.net.SocketException;public class ChatRoom {    public static void main(String[] args) throws Exception {        //启动发送线程和接收线程        //启动发送线程        new Thread(new UdpCilent(new DatagramSocket())).start();        //启动接收线程        new Thread(new UdpServer(new DatagramSocket(9999))).start();    }}
package com.edu_04;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.util.Scanner;public class UdpCilent implements Runnable{    DatagramSocket ds ;    public UdpCilent(DatagramSocket ds){        this.ds = ds;    }    @Override    public void run() {        try {            InetAddress address = InetAddress.getByName("192.168.20.255");            int port = 9999;            //2.创建键盘录入对象            Scanner sc = new Scanner(System.in);            String line;            while ((line=sc.nextLine())!=null) {                //键盘录入的数据line                byte[] buf = line.getBytes();                int length = buf.length;                DatagramPacket dp = new DatagramPacket(buf, length, address, port);                //发送数据包                ds.send(dp);            }            //释放资源            ds.close();        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}
package com.edu_04;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.SocketException;public class UdpServer implements Runnable{    DatagramSocket ds ;    public UdpServer(DatagramSocket ds){        this.ds = ds;    }    @Override    public void run() {        try {            //接受来自客户端的数据            while (true) {                //创建数据包                byte[] buf = new byte[1024];                int length = buf.length;                DatagramPacket dp = new DatagramPacket(buf, length);                //接受来自客户端的数据                ds.receive(dp);                //获取发送信息的人的ip地址                String ip = dp.getAddress().getHostAddress();                //解析数据包中的数据                byte[] data = dp.getData();                int len = dp.getLength();                System.out.println(ip+":"+new String(data, 0, len));            }        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}

1.10 多线程实现聊天室(相当于是将发送数据端和接收数据端合并)

二:TCP协议要点
2.1 TCP协议:(写一个demo)

特点:    1.需要建立通道    2.传送大量数据无限制    3.面向连接    4.可靠    5.速度慢

TCp协议书写步骤:
发送端:
TCP协议发送数据步骤:

A:创建TCP协议发送端Socket对象指定服务器IP及端口Socket sk = new Socket("192.168.3.120" , 9527) ;B:获取输出流,并写数据OutputStream outputStream = sk.getOutputStream() ;outputStream.write("hello,TCP我来了".getBytes()) ;C:释放资源sk.close() ;* java.net.ConnectException: Connection refused: connectTCP协议是不能直接运行客户端的,必须先运行服务器。因为他是一种可靠的协议。
package com.edu_05;import java.io.IOException;import java.io.OutputStream;import java.net.Socket;import java.net.UnknownHostException;public class TcpClient {    public static void main(String[] args) throws Exception {        //创建tcp协议发送端的socket对象        //public Socket(String host,int port)        Socket sk = new Socket("192.168.20.254", 10086);        //2.public OutputStream getOutputStream()throws IOException        //从通道中获取输出流对象        OutputStream os = sk.getOutputStream();        //3.给通道中写数据        os.write("hello".getBytes());        //4.释放资源        sk.close();    }}

接收端:
TCP协议接收数据步骤:

A:创建TCP协议接收端Socket对象    ServerSocket ss = new ServerSocket(9527) ;B:监听客户端连接    Socket sk = ss.accept() ;C:获取输入流,并读取数据,显示在控制台    // 读取数据    byte[] bytes = new byte[1024] ;    int len = inputStream.read(bytes) ;    // public InetAddress getInetAddress()获取IP地址    InetAddress inetAddress = sk.getInetAddress() ;    String ip = inetAddress.getHostAddress() ;    // 输出    System.out.println(ip + "发来数据是: " + new String(bytes , 0 , len));D:释放资源    sk.close() ;            
package com.edu_05;import java.io.IOException;import java.io.InputStream;import java.net.ServerSocket;import java.net.Socket;public class TcpServer {    public static void main(String[] args) throws Exception {        //1.创建服务器端的sokeck对象        //public ServerSocket(int port)throws IOException        ServerSocket ss = new ServerSocket(10086);        //2.坚挺来自客户端的连接        //public Socket accept()throws IOException侦听并接受到此套接字的连接。此方法在连接传入之前一直阻塞。         Socket sk = ss.accept();        //3.从通道中读取来自客户端的数据        InputStream is = sk.getInputStream();        //4.读取is        byte[] buf = new byte[1024];        int len = is.read(buf);        System.out.println(new String(buf, 0, len));        //5.释放资源        sk.close();    }}

2.2
用TCP协议写一个数据的发送和接收,接收端接收到数据之后给发送端一个反馈

package com.edu_06;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;import java.net.UnknownHostException;public class TcpClient {    public static void main(String[] args) throws Exception {        //创建tcp发送端的sockt对象        Socket sk = new Socket("192.168.20.254", 10000);        //从通道中获取输出流        OutputStream os = sk.getOutputStream();        //网通道中写数据        os.write("今晚约吗".getBytes());        //接受来自服务器端的反馈        InputStream is = sk.getInputStream();        //解析is        byte[] buf = new byte[1024];        int len = is.read(buf);        System.out.println(new String(buf, 0, len));        //释放资源        sk.close();    }}
package com.edu_06;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;public class TcpServer {    public static void main(String[] args) throws Exception {        //创建服务器端的socket对象        ServerSocket ss = new ServerSocket(10000);        //监听来自客户端的连接        Socket sk = ss.accept();        //从通道中获取输入流读取数据        InputStream is = sk.getInputStream();        //解析is        byte[] buf = new byte[1024];        int len = is.read(buf);        System.out.println(new String(buf, 0, len));        //给客户端一个反馈        OutputStream os = sk.getOutputStream();        os.write("不约".getBytes());        //释放资源        sk.close();         }}

2.3
以2.3的案例代码为基础,画图讲解tcp协议数据的发送和接收
这里写图片描述
2.4
需求: 客户端键盘录入数据,服务器端接收数据在控制台输出

package com.edu_07;import java.io.IOException;import java.io.OutputStream;import java.net.Socket;import java.net.UnknownHostException;import java.util.Scanner;public class TcpClient {    public static void main(String[] args) throws Exception {        //创建tcp发送端socket对象        Socket sk = new Socket("192.168.20.254", 20000);        //创建键盘录入对象        Scanner sc = new Scanner(System.in);        String line;        while ((line=sc.nextLine())!=null) {            //将line这个数据写如通道            OutputStream os = sk.getOutputStream();            os.write(line.getBytes());        }        sk.close();    }}
package com.edu_07;import java.io.IOException;import java.io.InputStream;import java.net.ServerSocket;import java.net.Socket;public class TcpServer {    public static void main(String[] args) throws Exception {        //创建服务器端的socket对象        ServerSocket ss = new ServerSocket(20000);        //监听来自客户端的连接        Socket sk = ss.accept();        while (true) {            InputStream is = sk.getInputStream();            byte[] buf = new byte[1024];            int len = is.read(buf);            System.out.println(new String(buf, 0, len));        }           }}

2.5
需求:客户端键盘录入数据,服务端将数据写入文件

package com.edu_08;import java.io.BufferedWriter;import java.io.IOException;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.net.Socket;import java.net.UnknownHostException;import java.util.Scanner;public class TcpClient {    public static void main(String[] args) throws Exception {        //创建tcp客户端socket对象        Socket sk = new Socket("192.168.20.254", 10010);        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sk.getOutputStream()));        //创建键盘录入对象        Scanner sc = new Scanner(System.in);        String line;        while ((line=sc.nextLine())!=null) {            //往通道中写数据,一次写一行            bw.write(line);            bw.newLine();            bw.flush();        }        sk.close();    }}
package com.edu_08;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileWriter;import java.io.IOException;import java.io.InputStreamReader;import java.net.ServerSocket;import java.net.Socket;public class TcpServer {    public static void main(String[] args) throws Exception {        //创建服务器端的socket对象        ServerSocket ss = new ServerSocket(10010);        //监听客户端连接        Socket sk = ss.accept();        //从sk的通道中读取数据,一次读取一行        BufferedReader br = new BufferedReader(new InputStreamReader(sk.getInputStream()));        BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));        //一次读取一行数据        String line;        while ((line=br.readLine())!=null) {            //line就是已经读取到的数据,我们现在需要将line这个数据写入文件            bw.write(line);            bw.newLine();            bw.flush();        }        sk.close();        bw.close();        br.close();    }}

2.6
需求:客户端读取文本文件中的内容发送给服务端,服务端将内容控制台输出

package com.edu_09;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileReader;import java.io.IOException;import java.io.OutputStreamWriter;import java.net.Socket;import java.net.UnknownHostException;public class TcpClient {    public static void main(String[] args) throws Exception {        //创建socket对象        Socket sk = new Socket("192.168.20.254", 2000);        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sk.getOutputStream()));        //读取文本一次读取一行        BufferedReader br = new BufferedReader(new FileReader("a.txt"));        String line;        while ((line=br.readLine())!=null) {            //line就是我读取到的数据,我需要将这个数据写入通道,一次写一行            bw.write(line);            bw.newLine();            bw.flush();        }        //释放资源        br.close();        bw.close();        sk.close();         }}
package com.edu_09;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.ServerSocket;import java.net.Socket;public class TcpServer {    public static void main(String[] args) throws Exception {        //创建服务器端的socket对象        ServerSocket ss = new ServerSocket(2000);        //蒋婷来自于客户端的连接        Socket sk = ss.accept();        //创建BufferedReader一次读取一行数据        BufferedReader br = new BufferedReader(new InputStreamReader(sk.getInputStream()));        String line;        while ((line=br.readLine())!=null) {            System.out.println(line);        }        //释放资源        br.close();        sk.close();         }}

2.7
需求: 上传文本文件

客户端:    a: 读取文本文件中的数据    b: 发送到服务器端服务器:    a: 读取流通道中的数据    b: 把数据写入到文本文件中

2.8
运用多线程改进2.7

package com.edu_10;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileReader;import java.io.IOException;import java.io.OutputStreamWriter;import java.net.Socket;import java.net.UnknownHostException;public class TcpClient {    public static void main(String[] args) throws Exception {        //创建socket对象        Socket sk = new Socket("192.168.20.254", 2000);        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sk.getOutputStream()));        //读取文本一次读取一行        BufferedReader br = new BufferedReader(new FileReader("InetAddressDemo.java"));        String line;        while ((line=br.readLine())!=null) {            //line就是我读取到的数据,我需要将这个数据写入通道,一次写一行            bw.write(line);            bw.newLine();            bw.flush();        }        //释放资源        br.close();        bw.close();        sk.close();         }}
package com.edu_10;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileWriter;import java.io.IOException;import java.io.InputStreamReader;import java.net.ServerSocket;import java.net.Socket;public class TcpServer {    public static void main(String[] args) throws Exception {        //创建服务器端的socket对象        ServerSocket ss = new ServerSocket(2000);        while (true) {            //蒋婷来自于客户端的连接            Socket sk = ss.accept();            //启动一个子线程,去执行复制文件的动作            new Thread(new ServerThread(sk)).start();        }           }}
package com.edu_10;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileWriter;import java.io.IOException;import java.io.InputStreamReader;import java.net.Socket;public class ServerThread implements Runnable{    Socket sk;    public ServerThread(Socket sk){        this.sk = sk;    }    @Override    public void run() {        try {            //创建BufferedReader一次读取一行数据            BufferedReader br = new BufferedReader(new InputStreamReader(sk.getInputStream()));            BufferedWriter bw = new BufferedWriter(new FileWriter(UUIDUtils.getFileName()));            String line;            while ((line=br.readLine())!=null) {                bw.write(line);                bw.newLine();                bw.flush();                //System.out.println(line);            }        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}
package com.edu_10;import java.util.UUID;import org.junit.Test;public class UUIDUtils {    @Test    public static String getFileName(){        String fileName = UUID.randomUUID().toString();        fileName = fileName.replaceAll("-", "")+".txt";        return fileName;    }}

2.9
提问:我们以后倒是使用udp协议还是tcp协议呢?
在咱们以后使用的软件当中基本都是udp和tcp混用的

原创粉丝点击