黑马程序员------网络编程

------- android培训、java培训、期待与您交流! ----------

黑马程序员------网络编程

1.1 InetAddress

InetAddress:构造方法私有,不能直接创建对象。

InetAddress getByName(String host):在给定主机名的情况下确定主机的ip地址。

InetAddress getLocalHost():返回本地主机。

InetAddress[] getAllByName(String host)

ip.getHostAddress(), 

ip.getHostName()

 1 示例1:
 2 import java.net.InetAddress;
 3 
 4 public class Demo1 {
 5     public static void main(String[] args) throws Exception {
 6         
 7         InetAddress i = InetAddress.getLocalHost();
 8         System.out.println(i);
 9         
10         i = InetAddress.getByName("www.baidu.com");
11         System.out.println(i);
12         System.out.println(i.getHostAddress());
13         
14         System.out.println(i.getHostName());
15     }
16 }

输出:
XP-201304252326/10.6.147.2
www.baidu.com/61.135.169.105
61.135.169.105
www.baidu.com

 

2.1 Socket
Socket就是为网络服务提供的一种机制。
通信的两端都有Socket。
网络通信其实就是Socket间的通信。
数据在两个Socket间通过IO传输。

 

3.1 UDP传输

①:只要是网络传输,必须有socket 。
②:数据一定要封装到数据包中,数据包中包括目的地址、端口、数据等信息。

直接操作udp不可能,对于java语言应该将udp封装成对象,易于我们的使用,这个对象就是DatagramSocket. 封装了udp传输协议的socket对象。

因为数据包中包含的信息较多,为了操作这些信息方便,也一样会将其封装成对象。这个数据包对象就是:DatagramPacket.通过这个对象中的方法,就可以获取到数据包中的各种信息。

DatagramSocket具备发送和接受功能,在进行udp传输时,需要明确一个是发送端,一个是接收端。

udp的发送端:
①:建立udp的socket服务,创建对象时如果没有明确端口,系统会自动分配一个未被使用的端口。
②:明确要发送的具体数据。
③:将数据封装成了数据包。
④:用socket服务的send方法将数据包发送出去。
⑤:关闭资源。

udp的接收端:
①:创建udp的socket服务,必须要明确一个端口,作用在于,只有发送到这个端口的数据才是这个接收端可以处理的数据。
②:定义数据包,用于存储接收到数据。
③:通过socket服务的接收方法将收到的数据存储到数据包中。
④:通过数据包的方法获取数据包中的具体数据内容,比如ip、端口、数据等等。
⑤:关闭资源。

示例1:演示接收端和发送端间的通讯:

 1 示例1:
 2 发送端(客户端)
 3 import java.net.*;
 4 class  UdpSend{
 5         public static void main(String[] args)throws Exception {
 6                 // 1,建立udp的socket服务。
 7                 DatagramSocket ds = new DatagramSocket(8888);//指定发送端口,这个可以不指定,系统会随机分配。
 8                 // 2,明确要发送的具体数据。
 9                 String text = "udp传输演示 哥们来了";
10                 byte[] buf = text.getBytes();
11                 // 3,将数据封装成了数据包。
12                 DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("10.1.31.127"),10000);
13                 // 4,用socket服务的send方法将数据包发送出去。
14                 ds.send(dp);
15                 // 5,关闭资源。
16                 ds.close();
17         }
18 }
19 
20 接收端(服务器端)
21 
22 import java.net.*;
23 class UdpRece {
24         public static void main(String[] args) throws Exception{
25                 // 1,创建udp的socket服务。
26                 DatagramSocket ds = new DatagramSocket(10000);//必须指定,并且和上面的端口号一样!
27                 // 2,定义数据包,用于存储接收到数据。先定义字节数组,数据包会把数据存储到字节数组中。
28                 byte[] buf = new byte[1024];
29                 DatagramPacket dp = new DatagramPacket(buf,buf.length);
30                 // 3,通过socket服务的接收方法将收到的数据存储到数据包中。
31                 ds.receive(dp);//该方法是阻塞式方法。
32                 // 4,通过数据包的方法获取数据包中的具体数据内容,比如ip,端口,数据等等。
33                 String ip = dp.getAddress().getHostAddress();
34                 int port = dp.getPort();
35                 String text = new String(dp.getData(),0,dp.getLength());//将字节数组中的有效部分转成字符串。
36                 System.out.println(ip+":"+port+"--"+text);
37                 // 5,关闭资源。
38                 ds.close();
39         }
40 }

 

练习(示例2):

通过键盘录入获取要发送的信息。
将发送和接收分别封装到两个线程中。

 1 示例2:
 2 import java.io.*;
 3 import java.net.*;
 4 
 5 
 6 //客户端,发送端
 7 class Send implements Runnable {
 8     private DatagramSocket ds;
 9 
10     public Send(DatagramSocket ds) {
11         super();
12         this.ds = ds;
13     }
14 
15     @Override
16     public void run() {
17         try {
18             BufferedReader br = new BufferedReader(new InputStreamReader(
19                     System.in));//数据源是键盘录入
20             String line;
21             while ((line = br.readLine()) != null) {
22                 byte[] buf = line.getBytes();
23                 DatagramPacket dp = new DatagramPacket(buf, buf.length,
24                         InetAddress.getByName("localhost"), 10225);
25 
26                 ds.send(dp);
27             }
28         } catch (IOException e) {
29             e.printStackTrace();
30         }
31     }
32 }
33 
34 // 服务器端,接收端
35 class Rece implements Runnable {
36     private DatagramSocket ds;
37 
38     public Rece(DatagramSocket ds) {
39         super();
40         this.ds = ds;
41     }
42 
43 44     public void run() {
45         try {
46             while (true) {
47                 byte[] buf = new byte[1024];
48 
49                 DatagramPacket dp = new DatagramPacket(buf, 0, buf.length);
50                 ds.receive(dp);
51 
52                 String ip = dp.getAddress().getHostAddress();
53                 String data = new String(dp.getData(), 0, dp.getLength());
54 
55                 System.out.println(ip + "     " + data);
56             }
57         } catch (Exception e) {
58             e.printStackTrace();
59         }
60     }
61 }
62 
63 public class Demo6 {
64     public static void main(String[] args) throws Exception {
65         DatagramSocket sendDs = new DatagramSocket();
66         DatagramSocket receDs = new DatagramSocket(10225);
67         new Thread(new Send(sendDs)).start();
68         new Thread(new Rece(receDs)).start();
69     }
70 }

 


输出:
你好
127.0.0.1 你好
你好
127.0.0.1 你好

 

 

4.1 TCP传输

两个端点的建立连接后会有一个传输数据的通道,这通道称为流,而且是建立在网络基础上的流,称之为socket流。该流中既有读取,也有写入。

tcp的两个端点:一个是客户端,一个是服务端。
客户端:对应的对象,Socket
服务端:对应的对象,ServerSocket

4.1.1TCP客户端:
①:建立tcp的socket服务,最好明确具体的地址和端口。这个对象在创建时,就已经可以对指定ip和端口进行连接(三次握手)。
②:如果连接成功,就意味着通道建立了,socket流就已经产生了。只要获取到socket流中的读取流和写入流即可,只要通过getInputStream和getOutputStream就可以获取两个流对象。
③:关闭资源。

1 import java.net.*;
2 import java.io.*;
3 //需求:客户端给服务器端发送一个数据。
4 class  TcpClient{
5         public static void main(String[] args) throws Exception{
6                 Socket s = new Socket("10.1.31.69",10002);
7                 OutputStream out = s.getOutputStream();//获取了socket流中的输出流对象。
8                 out.write("tcp演示,哥们又来了!".getBytes());
9                 s.close();



4.1.2TCP服务端:
①:创建服务端socket服务,并监听一个端口。
②:服务端为了给客户端提供服务,获取客户端的内容,可以通过accept方法获取连接过来的客户端对象。
③:可以通过获取到的socket对象中的socket流和具体的客户端进行通讯。
④:如果通讯结束,关闭资源。注意:要先关客户端,再关服务端。

 1 class  TcpServer{
 2         public static void main(String[] args) throws Exception{
 3                 ServerSocket ss = new ServerSocket(10002);//建立服务端的socket服务
 4                 Socket s = ss.accept();//获取客户端对象
 5                 String ip = s.getInetAddress().getHostAddress();
 6                 System.out.println(ip+".....connected");//打印下作为连接上的标志
 7 
 8                 // 可以通过获取到的socket对象中的socket流和具体的客户端进行通讯。
 9                 InputStream in = s.getInputStream();//读取客户端的数据,使用客户端对象的socket读取流
10                 byte[] buf = new byte[1024];
11                 int len = in.read(buf);
12                 String text = new String(buf,0,len);
13                 System.out.println(text);
14                 // 如果通讯结束,关闭资源。注意:要先关客户端,在关服务端。
15                 s.close();
16                 ss.close();
17         }
18 }

 

PS:这个例子只是单方面的输入!

 

4.1.3 需求:演示双向对话(示例3):

 1 示例3:
 2 双向对话
 3 
 4 客户端:
 5  6 //TCP双向对话
 7 
 8 import java.io.InputStream;
 9 import java.io.OutputStream;
10 import java.net.Socket;
11 
12 public class Demo10 {
13     public static void main(String[] args) throws Exception {
14         Socket s = new Socket("localhost",10036);
15         
16         OutputStream out = s.getOutputStream();
17         
18         out.write("你好,服务器!我是刘昭!".getBytes());
19         s.shutdownOutput();//注意!!!关闭标签
20         InputStream is = s.getInputStream();
21         byte []buf = new byte[1024];
22         int len = is.read(buf);
23             System.out.println(new String(buf,0,len));
24         s.close();
25     }
26 }
27 
28 服务器端
29 
30 31 //TCP双向输入输出
32 
33 import java.io.*;
34 import java.net.*;
35 36 37 
38 public class Demo11 {
39     public static void main(String[] args) throws Exception {
40         ServerSocket ss = new ServerSocket(10036);
41         Socket s = ss.accept();
42         
43         String ip = s.getInetAddress().getHostAddress();
44         System.out.println(ip+"..........connected!");
45         
46         InputStream in = s.getInputStream();
47         byte[] buf = new byte[1024];
48         /*int len = in.read(buf);
49         System.out.println(new String(buf,0,len));*/
50         int len;
51         while((len = in.read(buf)) != -1){
52             System.out.println(new String(buf,0,len));
53         }
54         OutputStream os = s.getOutputStream();
55         
56         os.write("刘昭你好!我是服务器!".getBytes());
57         
58         s.close();
59         ss.close();
60     }
61 }

 

4.1.4总结:对于UDP和TCP,既可以定义输出流也可以创建输入流,具体情况根据需要构建;

比如:我们需要客户端给服务器端发送数据,服务器端再给客户端反馈数据;

那么就要在客户端和服务器端分别多加一个输入流和输出流!否则,发不出去,收不到!

 

5.1 利用TCP上传文件

从客户端上传到服务器端,其实本质上也就是复制!

需求:利用TCP上传图片(注意图片是2进制文件,必须是字节流,否则读取不出来!),示例4:

 1 示例4:
 2 
 3 import java.io.*;
 4 import java.net.*;
 5 
 6 public class Demo16 {
 7     public static void main(String[] args) throws Exception {
 8         Socket s = new Socket("localhost",10256);
 9         FileInputStream fis = new FileInputStream("E:/DSC_2451.jpg"); 
10         
11         OutputStream os = s.getOutputStream();
12         
13         byte []buf = new byte[1024];
14         int len;
15         while((len = fis.read(buf)) != -1){
16             os.write(buf);
17         }
18         s.shutdownOutput();
19         InputStream in = s.getInputStream();
20         byte []b = new byte[1024];
21         int i = in.read(b);
22         System.out.println(new String(b,0,i));
23         fis.close();
24         s.close();
25     }
26 }    
27 
28 服务器端
29 
30 import java.io.*;
31 import java.net.*;
32 
33 public class Demo17 {
34     public static void main(String[] args) throws Exception {
35         
36         ServerSocket ss = new ServerSocket(10256);
37         Socket s = ss.accept();
38         
39         String ip = s.getInetAddress().getHostAddress();
40         System.out.println(ip+".........connected");
41         
42         InputStream is = s.getInputStream();
43         FileOutputStream fos = new FileOutputStream("E:/我的照片0.jpg");
44         
45         byte []b = new byte[1024];
46         int len;
47         while((len = is.read(b)) != -1){
48             fos.write(b);
49         }
50         
51         OutputStream os = s.getOutputStream();
52         os.write("上传成功!".getBytes());
53         
54         s.close();
55         ss.close();
56     }
57 }

 

 

5.1.2 总结:

对于网络编程而言,重要的是理解其步骤,按照步骤的需要,一步步搭建根基!
客户端和服务端需要交互,那么就要构建相对应的流,供其输入和输出!
对于阻塞式方法,一定要注意,提供停止标签!
对于PrintWriter ,记得用println而不是write;不要忘了加上true,自动刷新!

 

 

6 案例:题目:上传文件,多客户端上传,并且保证不会因为文件的名称而重复!

 1 客户端:
 2 
 3 import java.io.*;
 4 
 5 import java.net.*;
 6 
 7 public class Demo22 {
 8     public static void main(String[] args) throws Exception {
 9         Socket s = new Socket("localhost", 12036);
10         
11         BufferedReader br = new BufferedReader(new FileReader("E:/你好.txt"));
12         PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
13         
14         BufferedReader br2 = new BufferedReader(new InputStreamReader(s.getInputStream()));
15         
16         
17         String line;
18         while((line = br.readLine()) != null){
19             pw.println(line);
20         }
21         s.shutdownOutput();
22         
23         String str = br2.readLine();
24         System.out.println(str);
25         s.close();
26     }
27 }
28 
29 服务器端:
30 
31 import java.io.*;
32 import java.net.*;
33 
34 class MyUpdate implements Runnable{
35     private Socket s;
36 
37     public MyUpdate(Socket s) {
38         super();
39         this.s = s;
40     }
41 
42     @Override
43     public void run() {
44         
45         String ip = s.getInetAddress().getHostAddress();
46         System.out.println(ip+".........connected!");
47         int count = 0;
48         try {
49             BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
50             File file = new File("E:/");
51             File f = new File(file,"你好"+count+".txt");
52             while(f.exists()){//如果写成if,就不可以!
53                 f = new File(file,"你好"+(++count)+".txt"); 
54             }
55             PrintWriter pw = new PrintWriter(new FileWriter(f),true);
56             PrintWriter pw2 = new PrintWriter(s.getOutputStream(),true);
57             
58             String line;
59             while((line = br.readLine()) != null){
60                 pw.println(line);
61             }
62             
63             pw2.println("恭喜您,上传成功!");
64             s.close();
65         } catch (Exception e) {
66             e.printStackTrace();
67         }
68     }
69 }
70 
71 public class Demo23 {
72     public static void main(String[] args) throws Exception {
73         
74         ServerSocket ss = new ServerSocket(12036);
75         while(true){
76             Socket s = ss.accept();
77             new Thread(new MyUpdate(s)).start();
78         }
79     }
80 }

 

转载于:https://www.cnblogs.com/jiandonn/p/4579461.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值