java-网络编程

发布时间 2023-11-17 19:57:19作者: 索静丨LLH

第十四章 网络编程

引入

【1】网络编程:

把分布在不同地理区域的计算机与专门的外部设备用通信线路互连成一个规模大、功能强的网络系统,从而使众多的计算机可以方便地互相传递信息、共享硬件、软件、数据信息等资源。

设备之间在网络中进行数据的传输,发送/接收数据。

  

【2】通信两个重要的要素:IP+PORT 

 

域名:www.baidu.com      ------>DNS服务器解析 ----> IP地址

          www.mashibing.com

          www.sina.com

          www.wanda.com

          www.bbbb.com 

 

【3】设备之间进行传输的时候,必须遵照一定的规则 ---》通信协议:

 

 

【4】TCP协议:可靠的

建立连接:  三次握手 

 

释放连接:四次挥手 

  

【5】UDP协议:不可靠的

  

InetAddress,InetSocketAddress

前情提要:File   ---》   封装盘符一个文件 

【1】InetAddress   ---》 封装了IP 

 1 public class Test01 {
 2     //这是一个main方法,是程序的入口:
 3     public static void main(String[] args) throws UnknownHostException {
 4         //封装IP:
 5         //InetAddress ia = new InetAddress();不能直接创建对象,因为InetAddress()被default修饰了。
 6         InetAddress ia = InetAddress.getByName("192.168.199.217");
 7         System.out.println(ia);
 8         InetAddress ia2 = InetAddress.getByName("localhost");//localhost指代的是本机的ip地址
 9         System.out.println(ia2);
10         InetAddress ia3 = InetAddress.getByName("127.0.0.1");//127.0.0.1指代的是本机的ip地址
11         System.out.println(ia3);
12         InetAddress ia4 = InetAddress.getByName("LAPTOP-CRIVSRRU");//封装计算机名
13         System.out.println(ia4);
14         InetAddress ia5 = InetAddress.getByName("www.mashibing.com");//封装域名
15         System.out.println(ia5);
16         System.out.println(ia5.getHostName());//获取域名
17         System.out.println(ia5.getHostAddress());//获取ip地址
18     }
19 }
 

【2】InetSocketAddress  ---》封装了IP,端口号

 1 public class Test02 {
 2     //这是一个main方法,是程序的入口:
 3     public static void main(String[] args) {
 4         InetSocketAddress isa = new InetSocketAddress("192.168.199.217",8080);
 5         System.out.println(isa);
 6         System.out.println(isa.getHostName());
 7         System.out.println(isa.getPort());
 8         InetAddress ia = isa.getAddress();
 9         System.out.println(ia.getHostName());
10         System.out.println(ia.getHostAddress());
11     }
12 }

 

网络通信原理--套接字

  

基于TCP的网络编程

功能:模拟网站的登录,客户端录入账号密码,然后服务器端进行验证。

 

功能分解1:单向通信

功能:客户端发送一句话到服务器:

客户端:

 1 public class TestClient {//客户端
 2     //这是一个main方法,是程序的入口:
 3     public static void main(String[] args) throws IOException {
 4         //1.创建套接字:指定服务器的ip和端口号:
 5         Socket s = new Socket("192.168.199.217",8888);
 6         //2.对于程序员来说,向外发送数据 感受 --》利用输出流:
 7         OutputStream os = s.getOutputStream();
 8         DataOutputStream dos = new DataOutputStream(os);
 9         //利用这个OutputStream就可以向外发送数据了,但是没有直接发送String的方法
10         //所以我们又在OutputStream外面套了一个处理流:DataOutputStream
11         dos.writeUTF("你好");
12         //3.关闭流  +  关闭网络资源:
13         dos.close();
14         os.close();
15         s.close();
16     }
17 }

 

服务器:

 1 public class TestServer {//服务器
 2     //这是一个main方法,是程序的入口:
 3     public static void main(String[] args) throws IOException {
 4         //1.创建套接字: 指定服务器的端口号
 5         ServerSocket ss = new ServerSocket(8888);
 6         //2.等着客户端发来的信息:
 7         Socket s = ss.accept();//阻塞方法:等待接收客户端的数据,什么时候接收到数据,什么时候程序继续向下执行。
 8         //accept()返回值为一个Socket,这个Socket其实就是客户端的Socket
 9         //接到这个Socket以后,客户端和服务器才真正产生了连接,才真正可以通信了
10         //3.感受到的操作流:
11         InputStream is = s.getInputStream();
12         DataInputStream dis = new DataInputStream(is);
13         //4.读取客户端发来的数据:
14         String str = dis.readUTF();
15         System.out.println("客户端发来的数据为:"+str);
16         
17         //5.关闭流+关闭网络资源:
18         dis.close();
19         is.close();
20         s.close();
21         ss.close();
22     }
23 }

 

测试:

(1)先开启客户端还是先开启服务器:先开服务器,再开启客户端

侧面验证:先开客户端:出错:

  

功能分解2:双向通信

服务器端:

 1 package com.llh;
 2 
 3 import java.io.*;
 4 import java.net.ServerSocket;
 5 import java.net.Socket;
 6 
 7 
 8 public class TestServer {//服务器
 9     //这是一个main方法,是程序的入口:
10     public static void main(String[] args) throws IOException {
11         //1.创建套接字: 指定服务器的端口号
12         ServerSocket ss = new ServerSocket(8888);
13         //2.等着客户端发来的信息:
14         Socket s = ss.accept();//阻塞方法:等待接收客户端的数据,什么时候接收到数据,什么时候程序继续向下执行。
15         //accept()返回值为一个Socket,这个Socket其实就是客户端的Socket
16         //接到这个Socket以后,客户端和服务器才真正产生了连接,才真正可以通信了
17         //3.感受到的操作流:
18         InputStream is = s.getInputStream();
19         DataInputStream dis = new DataInputStream(is);
20         //4.读取客户端发来的数据:
21         String str = dis.readUTF();
22         System.out.println("客户端发来的数据为:"+str);
23         //向客户端输出一句话:---》操作流---》输出流
24         OutputStream os = s.getOutputStream();
25         DataOutputStream dos = new DataOutputStream(os);
26         dos.writeUTF("你好,我是服务器端,我接受到你的请求了");
27         //5.关闭流+关闭网络资源:
28         dos.close();
29         os.close();
30         dis.close();
31         is.close();
32         s.close();
33         ss.close();
34     }
35 }

 

客户端:

 1 import java.io.*;
 2 import java.net.Socket;
 3 
 4 public class TestClient {//客户端
 5     //这是一个main方法,是程序的入口:
 6     public static void main(String[] args) throws IOException {
 7         //1.创建套接字:指定服务器的ip和端口号:
 8         Socket s = new Socket("192.168.199.217",8888);
 9         //2.对于程序员来说,向外发送数据 感受 --》利用输出流:
10         OutputStream os = s.getOutputStream();
11         DataOutputStream dos = new DataOutputStream(os);
12         //利用这个OutputStream就可以向外发送数据了,但是没有直接发送String的方法
13         //所以我们又在OutputStream外面套了一个处理流:DataOutputStream
14         dos.writeUTF("你好");
15         //接收服务器端的回话--》利用输入流:
16         InputStream is = s.getInputStream();
17         DataInputStream dis = new DataInputStream(is);
18         String str = dis.readUTF();
19         System.out.println("服务器端对我说:"+str);
20         //3.关闭流  +  关闭网络资源:
21         dis.close();
22         is.close();
23         dos.close();
24         os.close();
25         s.close();
26     }
27 }

 

注意:关闭防火墙

功能分解3:对象流传送

封装的User类:

 1 import java.io.Serializable;
 2 
 3 public class User implements Serializable {
 4     private static final long serialVersionUID = 9050691344308365540L;
 5     private String name;
 6     private String pwd;
 7     public String getName() {
 8         return name;
 9     }
10     public void setName(String name) {
11         this.name = name;
12     }
13     public String getPwd() {
14         return pwd;
15     }
16     public void setPwd(String pwd) {
17         this.pwd = pwd;
18     }
19     public User(String name, String pwd) {
20         this.name = name;
21         this.pwd = pwd;
22     }
23 }

客户端:

 1 import java.io.*;
 2 import java.net.Socket;
 3 import java.util.Scanner;
 4 
 5 public class TestClient {//客户端
 6     //这是一个main方法,是程序的入口:
 7     public static void main(String[] args) throws IOException {
 8         //1.创建套接字:指定服务器的ip和端口号:
 9         Socket s = new Socket("192.168.199.217",8888);
10         //录入用户的账号和密码:
11         Scanner sc = new Scanner(System.in);
12         System.out.println("请录入您的账号:");
13         String name = sc.next();
14         System.out.println("请录入您的密码:");
15         String pwd = sc.next();
16         //将账号和密码封装为一个User的对象:
17         User user = new User(name,pwd);
18         //2.对于程序员来说,向外发送数据 感受 --》利用输出流:
19         OutputStream os = s.getOutputStream();
20         ObjectOutputStream oos = new ObjectOutputStream(os);
21         oos.writeObject(user);
22         //接收服务器端的回话--》利用输入流:
23         InputStream is = s.getInputStream();
24         DataInputStream dis = new DataInputStream(is);
25         boolean b = dis.readBoolean();
26         if(b){
27             System.out.println("恭喜,登录成功");
28         }else{
29             System.out.println("对不起,登录失败");
30         }
31         //3.关闭流  +  关闭网络资源:
32         dis.close();
33         is.close();
34         oos.close();
35         os.close();
36         s.close();
37     }
38 }

服务器:

 

 1 import java.io.*;
 2 import java.net.ServerSocket;
 3 import java.net.Socket;
 4 
 5 public class TestServer {//服务器
 6     //这是一个main方法,是程序的入口:
 7     public static void main(String[] args) throws IOException, ClassNotFoundException {
 8         //1.创建套接字: 指定服务器的端口号
 9         ServerSocket ss = new ServerSocket(8888);
10         //2.等着客户端发来的信息:
11         Socket s = ss.accept();//阻塞方法:等待接收客户端的数据,什么时候接收到数据,什么时候程序继续向下执行。
12         //accept()返回值为一个Socket,这个Socket其实就是客户端的Socket
13         //接到这个Socket以后,客户端和服务器才真正产生了连接,才真正可以通信了
14         //3.感受到的操作流:
15         InputStream is = s.getInputStream();
16         ObjectInputStream ois = new ObjectInputStream(is);
17         //4.读取客户端发来的数据:
18         User user = (User)(ois.readObject());
19         //对对象进行验证:
20         boolean flag = false;
21         if(user.getName().equals("娜娜")&&user.getPwd().equals("123123")){
22             flag = true;
23         }
24         //向客户端输出结果:---》操作流---》输出流
25         OutputStream os = s.getOutputStream();
26         DataOutputStream dos = new DataOutputStream(os);
27         dos.writeBoolean(flag);
28         //5.关闭流+关闭网络资源:
29         dos.close();
30         os.close();
31         ois.close();
32         is.close();
33         s.close();
34         ss.close();
35     }
36 }

 

功能分解4:加入完整的处理异常方式

服务器端:

 1 import java.io.*;
 2 import java.net.ServerSocket;
 3 import java.net.Socket;
 4 
 5 public class TestServer {//服务器
 6 
 7     //这是一个main方法,是程序的入口:
 8     public static void main(String[] args) {
 9         //1.创建套接字: 指定服务器的端口号
10         ServerSocket ss = null;
11         Socket s = null;
12         InputStream is = null;
13         ObjectInputStream ois = null;
14         OutputStream os = null;
15         DataOutputStream dos = null;
16         try {
17             ss = new ServerSocket(8888);
18             //2.等着客户端发来的信息:
19             s = ss.accept();//阻塞方法:等待接收客户端的数据,什么时候接收到数据,什么时候程序继续向下执行。
20             //accept()返回值为一个Socket,这个Socket其实就是客户端的Socket
21             //接到这个Socket以后,客户端和服务器才真正产生了连接,才真正可以通信了
22             //3.感受到的操作流:
23             is = s.getInputStream();
24             ois = new ObjectInputStream(is);
25             //4.读取客户端发来的数据:
26             User user = (User) (ois.readObject());
27             //对对象进行验证:
28             boolean flag = false;
29             if (user.getName().equals("娜娜") && user.getPwd().equals("123123")) {
30                 flag = true;
31             }
32             //向客户端输出结果:---》操作流---》输出流
33             os = s.getOutputStream();
34             dos = new DataOutputStream(os);
35             dos.writeBoolean(flag);
36         } catch (IOException | ClassNotFoundException e) {
37             e.printStackTrace();
38         } finally {
39             //5.关闭流+关闭网络资源:
40             try {
41                 if (dos != null) {
42                     dos.close();
43                 }
44             } catch (IOException e) {
45                 e.printStackTrace();
46             }
47             try {
48                 if (os != null) {
49                     os.close();
50                 }
51             } catch (IOException e) {
52                 e.printStackTrace();
53             }
54             try {
55                 if (ois != null) {
56                     ois.close();
57                 }
58             } catch (IOException e) {
59                 e.printStackTrace();
60             }
61             try {
62                 if (is != null) {
63                     is.close();
64                 }
65             } catch (IOException e) {
66                 e.printStackTrace();
67             }
68             try {
69                 if (s != null) {
70                     s.close();
71                 }
72             } catch (IOException e) {
73                 e.printStackTrace();
74             }
75             try {
76                 if (ss != null) {
77                     ss.close();
78                 }
79             } catch (IOException e) {
80                 e.printStackTrace();
81             }
82         }
83     }
84 }

客户端:

 

 1 import java.io.*;
 2 import java.net.Socket;
 3 import java.util.Scanner;
 4 
 5 public class TestClient {//客户端
 6 
 7     //这是一个main方法,是程序的入口:
 8     public static void main(String[] args) {
 9         //1.创建套接字:指定服务器的ip和端口号:
10         Socket s = null;
11         OutputStream os = null;
12         ObjectOutputStream oos = null;
13         InputStream is = null;
14         DataInputStream dis = null;
15         try {
16             s = new Socket("192.168.199.217", 8888);
17             //录入用户的账号和密码:
18             Scanner sc = new Scanner(System.in);
19             System.out.println("请录入您的账号:");
20             String name = sc.next();
21             System.out.println("请录入您的密码:");
22             String pwd = sc.next();
23             //将账号和密码封装为一个User的对象:
24             User user = new User(name, pwd);
25             //2.对于程序员来说,向外发送数据 感受 --》利用输出流:
26             os = s.getOutputStream();
27             oos = new ObjectOutputStream(os);
28             oos.writeObject(user);
29             //接收服务器端的回话--》利用输入流:
30             is = s.getInputStream();
31             dis = new DataInputStream(is);
32             boolean b = dis.readBoolean();
33             if (b) {
34                 System.out.println("恭喜,登录成功");
35             } else {
36                 System.out.println("对不起,登录失败");
37             }
38         } catch (IOException e) {
39             e.printStackTrace();
40         } finally {
41             //3.关闭流  +  关闭网络资源:
42             try {
43                 if (dis != null) {
44                     dis.close();
45                 }
46             } catch (IOException e) {
47                 e.printStackTrace();
48             }
49             try {
50                 if (is != null) {
51                     is.close();
52                 }
53             } catch (IOException e) {
54                 e.printStackTrace();
55             }
56             try {
57                 if (oos != null) {
58                     oos.close();
59                 }
60             } catch (IOException e) {
61                 e.printStackTrace();
62             }
63             try {
64                 if (os != null) {
65                     os.close();
66                 }
67             } catch (IOException e) {
68                 e.printStackTrace();
69             }
70             try {
71                 if (s != null) {
72                     s.close();
73                 }
74             } catch (IOException e) {
75                 e.printStackTrace();
76             }
77         }
78     }
79 }

 

功能分解5:多线程接收用户请求

遗留问题:服务器针对一个请求服务,之后服务器就关闭了(程序自然结束了)

现在需要解决:服务器必须一直在监听 ,一直开着,等待客户端的请求

在当前代码中,客户端不用动了

  

更改服务器代码:

 1 import java.io.*;
 2 import java.net.Socket;
 3 
 4 public class ServerThread extends Thread {//线程:专门处理客户端的请求
 5     InputStream is = null;
 6     ObjectInputStream ois = null;
 7     OutputStream os = null;
 8     DataOutputStream dos = null;
 9     Socket s = null;
10     public ServerThread(Socket s){
11         this.s = s;
12     }
13     @Override
14     public void run() {
15         try{
16             //2.等着客户端发来的信息:
17             is = s.getInputStream();
18             ois = new ObjectInputStream(is);
19             //4.读取客户端发来的数据:
20             User user = (User)(ois.readObject());
21             //对对象进行验证:
22             boolean flag = false;
23             if(user.getName().equals("娜娜")&&user.getPwd().equals("123123")){
24                 flag = true;
25             }
26             //向客户端输出结果:---》操作流---》输出流
27             os = s.getOutputStream();
28             dos = new DataOutputStream(os);
29             dos.writeBoolean(flag);
30         }catch (IOException | ClassNotFoundException e) {
31             e.printStackTrace();
32         }finally {
33             try {
34                 if(dos!=null){
35                     dos.close();
36                 }
37             } catch (IOException e) {
38                 e.printStackTrace();
39             }
40             try {
41                 if(os!=null){
42                     os.close();
43                 }
44             } catch (IOException e) {
45                 e.printStackTrace();
46             }
47             try {
48                 if(ois!=null){
49                     ois.close();
50                 }
51             } catch (IOException e) {
52                 e.printStackTrace();
53             }
54             try {
55                 if(is!=null){
56                     is.close();
57                 }
58             } catch (IOException e) {
59                 e.printStackTrace();
60             }
61         }
62     }
63 }

 

基于UDP的网络编程

TCP:

 客户端:Socket                                      

程序感受到的 使用流  :输出流

服务器端:  ServerSocket --->Socket     程序感受到的 使用流  :输入流

(客户端和服务器端地位不平等。)

 

UDP:

发送方:DatagramSocket   发送:数据包  DatagramPacket

接收方:DatagramSocket   接收:数据包  DatagramPacket

(发送方和接收方的地址是平等的。)

UDP案例:  完成网站的咨询聊天

 

功能分解1:单向通信

发送方:

 1 import java.io.IOException;
 2 import java.net.*;
 3 
 4 public class TestSend {//发送方:
 5     //这是一个main方法,是程序的入口:
 6     public static void main(String[] args) throws IOException {
 7         System.out.println("学生上线。。。");
 8         //1.准备套接字: 指定发送方的端口号
 9         DatagramSocket ds = new DatagramSocket(8888);
10         //2.准备数据包
11         String str = "你好";
12         byte[] bytes = str.getBytes();
13         /*
14         需要四个参数:
15         1.指的是传送数据转为字节数组
16         2.字节数组的长度
17         3.封装接收方的ip
18         4.指定接收方的端口号
19          */
20         DatagramPacket dp = new DatagramPacket(bytes,bytes.length, InetAddress.getByName("localhost"),9999);
21         //发送:
22         ds.send(dp);
23         //关闭资源
24         ds.close();
25     }
26 }

 

接收方:

 1 import java.io.IOException;
 2 import java.net.DatagramPacket;
 3 import java.net.DatagramSocket;
 4 import java.net.SocketException;
 5 
 6 public class TestReceive {//接收方
 7     //这是一个main方法,是程序的入口:
 8     public static void main(String[] args) throws IOException {
 9         System.out.println("老师上线了。。");
10         //1.创建套接字:指定接收方的端口
11         DatagramSocket ds = new DatagramSocket(9999);
12         //2.有一个空的数据包,打算用来接收  对方传过来的数据包:
13         byte[] b = new byte[1024];
14         DatagramPacket dp = new DatagramPacket(b,b.length);
15         //3.接收对方的数据包,然后放入我们的dp数据包中填充
16         ds.receive(dp);//接收完以后 dp里面就填充好内容了
17         //4.取出数据:
18         byte[] data = dp.getData();
19         String s = new String(data,0,dp.getLength());//dp.getLength()数组包中的有效长度
20         System.out.println("学生对我说:"+s);
21         //5.关闭资源:
22         ds.close();
23     }
24 }

 

功能分解2:双向通信

发送方:

 1 import java.io.IOException;
 2 import java.net.*;
 3 import java.util.Scanner;
 4 
 5 public class TestSend {//发送方:
 6     //这是一个main方法,是程序的入口:
 7     public static void main(String[] args) throws IOException {
 8         System.out.println("学生上线。。。");
 9         //1.准备套接字: 指定发送方的端口号
10         DatagramSocket ds = new DatagramSocket(8888);
11         //2.准备数据包
12         Scanner sc = new Scanner(System.in);
13         System.out.print("学生:");
14         String str = sc.next();
15         byte[] bytes = str.getBytes();
16         /*
17         需要四个参数:
18         1.指的是传送数据转为Z字节数组
19         2.字节数组的长度
20         3.封装接收方的ip
21         4.指定接收方的端口号
22          */
23         DatagramPacket dp = new DatagramPacket(bytes,bytes.length, InetAddress.getByName("localhost"),9999);
24         //发送:
25         ds.send(dp);
26         //接收老师发送回来的信息:
27         byte[] b = new byte[1024];
28         DatagramPacket dp2 = new DatagramPacket(b,b.length);
29         ds.receive(dp2);//接收完以后 dp2里面就填充好内容了
30         //取出数据:
31         byte[] data = dp2.getData();
32         String s = new String(data,0,dp2.getLength());//dp.getLength()数组包中的有效长度
33         System.out.println("老师对我说:"+s);
34         //关闭资源
35         ds.close();
36     }
37 }
 

接收方:

 1 import java.io.IOException;
 2 import java.net.DatagramPacket;
 3 import java.net.DatagramSocket;
 4 import java.net.InetAddress;
 5 import java.net.SocketException;
 6 import java.util.Scanner;
 7 
 8 public class TestReceive {//接收方
 9     //这是一个main方法,是程序的入口:
10     public static void main(String[] args) throws IOException {
11         System.out.println("老师上线了。。");
12         //1.创建套接字:指定接收方的端口
13         DatagramSocket ds = new DatagramSocket(9999);
14         //2.有一个空的数据包,打算用来接收  对方传过来的数据包:
15         byte[] b = new byte[1024];
16         DatagramPacket dp = new DatagramPacket(b,b.length);
17         //3.接收对方的数据包,然后放入我们的dp数据包中填充
18         ds.receive(dp);//接收完以后 dp里面就填充好内容了
19         //4.取出数据:
20         byte[] data = dp.getData();
21         String s = new String(data,0,dp.getLength());//dp.getLength()数组包中的有效长度
22         System.out.println("学生对我说:"+s);
23         //老师进行回复:
24         Scanner sc = new Scanner(System.in);
25         System.out.print("老师:");
26         String str = sc.next();
27         byte[] bytes = str.getBytes();
28         //封装数据,并且指定学生的ip和端口号
29         DatagramPacket dp2 = new DatagramPacket(bytes,bytes.length, InetAddress.getByName("localhost"),8888);
30         //发送:
31         ds.send(dp2);
32         //5.关闭资源:
33         ds.close();
34     }
35 }
 

功能分解3:加入完整的处理异常方式

发送方:

 1 import java.io.IOException;
 2 import java.net.*;
 3 import java.util.Scanner;
 4 
 5 public class TestSend {//发送方:
 6     //这是一个main方法,是程序的入口:
 7     public static void main(String[] args)  {
 8         System.out.println("学生上线。。。");
 9         //1.准备套接字: 指定发送方的端口号
10         DatagramSocket ds = null;
11         try {
12             ds = new DatagramSocket(8888);
13             //2.准备数据包
14             Scanner sc = new Scanner(System.in);
15             System.out.print("学生:");
16             String str = sc.next();
17             byte[] bytes = str.getBytes();
18         /*
19         需要四个参数:
20         1.指的是传送数据转为Z字节数组
21         2.字节数组的长度
22         3.封装接收方的ip
23         4.指定接收方的端口号
24          */
25             DatagramPacket dp = new DatagramPacket(bytes,bytes.length, InetAddress.getByName("localhost"),9999);
26             //发送:
27             ds.send(dp);
28             //接收老师发送回来的信息:
29             byte[] b = new byte[1024];
30             DatagramPacket dp2 = new DatagramPacket(b,b.length);
31             ds.receive(dp2);//接收完以后 dp2里面就填充好内容了
32             //取出数据:
33             byte[] data = dp2.getData();
34             String s = new String(data,0,dp2.getLength());//dp.getLength()数组包中的有效长度
35             System.out.println("老师对我说:"+s);
36         } catch (SocketException e) {
37             e.printStackTrace();
38         } catch (UnknownHostException e) {
39             e.printStackTrace();
40         } catch (IOException e) {
41             e.printStackTrace();
42         } finally {
43             //关闭资源
44             ds.close();
45         }
46     }
47 }

接收方:

 1 import java.io.IOException;
 2 import java.net.*;
 3 import java.util.Scanner;
 4 
 5 public class TestReceive {//接收方
 6     //这是一个main方法,是程序的入口:
 7     public static void main(String[] args){
 8         System.out.println("老师上线了。。");
 9         //1.创建套接字:指定接收方的端口
10         DatagramSocket ds = null;
11         try {
12             ds = new DatagramSocket(9999);
13             //2.有一个空的数据包,打算用来接收  对方传过来的数据包:
14             byte[] b = new byte[1024];
15             DatagramPacket dp = new DatagramPacket(b,b.length);
16             //3.接收对方的数据包,然后放入我们的dp数据包中填充
17             ds.receive(dp);//接收完以后 dp里面就填充好内容了
18             //4.取出数据:
19             byte[] data = dp.getData();
20             String s = new String(data,0,dp.getLength());//dp.getLength()数组包中的有效长度
21             System.out.println("学生对我说:"+s);
22             //老师进行回复:
23             Scanner sc = new Scanner(System.in);
24             System.out.print("老师:");
25             String str = sc.next();
26             byte[] bytes = str.getBytes();
27             //封装数据,并且指定学生的ip和端口号
28             DatagramPacket dp2 = new DatagramPacket(bytes,bytes.length, InetAddress.getByName("localhost"),8888);
29             //发送:
30             ds.send(dp2);
31         } catch (SocketException e) {
32             e.printStackTrace();
33         } catch (UnknownHostException e) {
34             e.printStackTrace();
35         } catch (IOException e) {
36             e.printStackTrace();
37         } finally {
38             //5.关闭资源:
39             ds.close();
40         }
41     }
42 }

 

功能分解4:正常通信

发送方:

 1 import java.io.IOException;
 2 import java.net.*;
 3 import java.util.Scanner;
 4 
 5 public class TestSend {//发送方:
 6     //这是一个main方法,是程序的入口:
 7     public static void main(String[] args)  {
 8         System.out.println("学生上线。。。");
 9         //1.准备套接字: 指定发送方的端口号
10         DatagramSocket ds = null;
11         try {
12             ds = new DatagramSocket(8888);
13             while(true){
14                 //2.准备数据包
15                 Scanner sc = new Scanner(System.in);
16                 System.out.print("学生:");
17                 String str = sc.next();
18                 byte[] bytes = str.getBytes();
19         /*
20         需要四个参数:
21         1.指的是传送数据转为Z字节数组
22         2.字节数组的长度
23         3.封装接收方的ip
24         4.指定接收方的端口号
25          */
26                 DatagramPacket dp = new DatagramPacket(bytes,bytes.length, InetAddress.getByName("localhost"),9999);
27                 //发送:
28                 ds.send(dp);
29                 if(str.equals("byebye")){
30                     System.out.println("学生下线。。");
31                     break;
32                 }
33                 //接收老师发送回来的信息:
34                 byte[] b = new byte[1024];
35                 DatagramPacket dp2 = new DatagramPacket(b,b.length);
36                 ds.receive(dp2);//接收完以后 dp2里面就填充好内容了
37                 //取出数据:
38                 byte[] data = dp2.getData();
39                 String s = new String(data,0,dp2.getLength());//dp.getLength()数组包中的有效长度
40                 System.out.println("老师对我说:"+s);
41             }
42         } catch (SocketException e) {
43             e.printStackTrace();
44         } catch (UnknownHostException e) {
45             e.printStackTrace();
46         } catch (IOException e) {
47             e.printStackTrace();
48         } finally {
49             //关闭资源
50             ds.close();
51         }
52     }
53 }

 

接收方:

 1 import java.io.IOException;
 2 import java.net.*;
 3 import java.util.Scanner;
 4 
 5 public class TestReceive {//接收方
 6     //这是一个main方法,是程序的入口:
 7     public static void main(String[] args){
 8         System.out.println("老师上线了。。");
 9         //1.创建套接字:指定接收方的端口
10         DatagramSocket ds = null;
11         try {
12             ds = new DatagramSocket(9999);
13             while(true){
14                 //2.有一个空的数据包,打算用来接收  对方传过来的数据包:
15                 byte[] b = new byte[1024];
16                 DatagramPacket dp = new DatagramPacket(b,b.length);
17                 //3.接收对方的数据包,然后放入我们的dp数据包中填充
18                 ds.receive(dp);//接收完以后 dp里面就填充好内容了
19                 //4.取出数据:
20                 byte[] data = dp.getData();
21                 String s = new String(data,0,dp.getLength());//dp.getLength()数组包中的有效长度
22                 System.out.println("学生对我说:"+s);
23                 if(s.equals("byebye")){
24                     System.out.println("学生已经下线了,老师也下线。。。");
25                     break;
26                 }
27                 //老师进行回复:
28                 Scanner sc = new Scanner(System.in);
29                 System.out.print("老师:");
30                 String str = sc.next();
31                 byte[] bytes = str.getBytes();
32                 //封装数据,并且指定学生的ip和端口号
33                 DatagramPacket dp2 = new DatagramPacket(bytes,bytes.length, InetAddress.getByName("localhost"),8888);
34                 //发送:
35                 ds.send(dp2);
36             }
37         } catch (SocketException e) {
38             e.printStackTrace();
39         } catch (UnknownHostException e) {
40             e.printStackTrace();
41         } catch (IOException e) {
42             e.printStackTrace();
43         } finally {
44             //5.关闭资源:
45             ds.close();
46         }
47     }
48 }