JAVASE_23_@网络编程-23

来源:互联网 发布:闲鱼怎么做淘宝链接 编辑:程序博客网 时间:2024/06/07 13:51
1,概述
双方网络通信---网络要素
1,找到对方IP地址
2,端口:逻辑端口   范围 0~65536
3,定义通信规则,这个通讯规则成为协议
国际组织定义了通用协议 TCP/IP


2,IP地址---java.net   InetAddress
网络中设备的标识
不易记忆,可用主机名
本地回环地址:127.0.0.1 主机名:localhost
方法getHostAddress()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.net.InetAddress;
import java.net.UnknownHostException;
 
public class IPDemo {
    public static void main(String[] args) throws UnknownHostException{
        InetAddress i = InetAddress.getLocalHost();
        System.out.println(i.toString());
        System.out.println("address="+i.getHostAddress());
        System.out.println("name="+i.getHostName());
         
        InetAddress[] ia= InetAddress.getAllByName("www.baidu.com");
        for(InetAddress ip:ia){
            System.out.println(ip.toString());
        }      
    }
}
Administer-PC/192.168.0.44
address=192.168.0.44
name=Administer-PC
www.baidu.com/61.135.169.105
www.baidu.com/61.135.169.125
3,端口号
用于标识进程的额逻辑地址,不同进程的标识
有效端口:0~~65535,其中0~1024系统使用或保留端口
4,传输协议
UDP---面向无连接
1.将数据及源和目的封装在数据包中,不需要建立连接
2.每个数据包的大小限制在64K
3.因无连接,是不可靠协议
4.不需要建立连接,速度快
应用:飞秋,视频会议,视频教学,桌面共享

TCP----面向有链接
1.建立连接,形成传输数据的通道
2.在连接中进行大量数据传输
3.通过三次握手完成连接,是可靠协议
4.必须建立连接,效率会稍低
应用:相当于打电话

5,Socket(套接字)
    ------单词翻译:插座----相当于码头
    -->所谓的网络编程就是socket编程
1,Socket就是为网络服务提供的一种机制
2,通信两端都有Socket
3,网络通信其实就是Socket间的通讯
4,数据在两个Socket间通过IO传输

6,UDP
UDP----->发送端
需求:通过udp传输方式,将一段文字数据发送出去。,
定义一个udp发送端。
思路:
1,建立updsocket服务。
2,提供数据,并将数据封装到数据包中。
3,通过socket服务的发送功能,将数据包发出去。
4,关闭资源。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class  UdpSend{
    public static void main(String[] args) throws Exception{
        //1,创建udp服务。通过DatagramSocket对象。
        DatagramSocket ds = new DatagramSocket(8888);//制定发送端端口为8888
        //2,确定数据,并封装成数据包。DatagramPacket(byte[] buf, int length, InetAddress address, int port) 
        byte[] buf = "udp ge men lai le ".getBytes();
        DatagramPacket dp = 
            new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.254"),10000);
        //3,通过socket服务,将已有的数据包发送出去。通过send方法。
        ds.send(dp);
        //4,关闭资源。
        ds.close();
    }
}
图例:
 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
UDP----->接收端
需求:定义一个应用程序,用于接收udp协议传输的数据并处理的。
定义udp的接收端。
思路:
1,定义udpsocket服务。通常会监听一个端口。其实就是给这个接收网络应用程序定义数字标识。
 方便于明确哪些数据过来该应用程序可以处理。
2,定义一个数据包,因为要存储接收到的字节数据。
因为数据包对象中有更多功能可以提取字节数据中的不同数据信息。
3,通过socket服务的receive方法将收到的数据存入已定义好的数据包中。
4,通过数据包对象的特有功能。将这些不同的数据取出。打印在控制台上。
5,关闭资源。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class  UdpRece{
    public static void main(String[] args) throws Exception{
        //1,创建udp socket,建立端点。
        DatagramSocket ds = new DatagramSocket(10000);//接收端必须监听一个端口
        //2,定义数据包。用于存储数据。
        byte[] buf = new byte[1024];
        DatagramPacket dp = new DatagramPacket(buf,buf.length);
        //3,通过服务的receive方法将收到数据存入数据包中。
        ds.receive(dp);//阻塞式方法。
        //4,通过数据包的方法获取其中的数据。
        String ip = dp.getAddress().getHostAddress();
        String data = new String(dp.getData(),0,dp.getLength());
        int port = dp.getPort();
        System.out.println(ip+"::"+data+"::"+port);
        //5,关闭资源
        ds.close();
    }
}
7,UDP--键盘录入方式数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class  UdpSend2{
    public static void main(String[] args) throws Exception{
        DatagramSocket ds = new DatagramSocket();
        BufferedReader bufr = 
            new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        while((line=bufr.readLine())!=null){
            if("886".equals(line))
                break;
            byte[] buf = line.getBytes();
            DatagramPacket dp = 
                new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.255"),10001);
            ds.send(dp);
        }
        ds.close();
    }
}
8,UDP-----Dos聊天室
编写一个聊天程序。
有收数据的部分,和发数据的部分。
这两部分需要同时执行。
那就需要用到多线程技术。
一个线程控制收,一个线程控制发。
因为收和发动作是不一致的,所以要定义两个run方法。
而且这两个方法要封装到不同的类中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.io.*;
import java.net.*;
class Send implements Runnable{
    private DatagramSocket ds;
    public Send(DatagramSocket ds){
        this.ds = ds;
    }
    public void run(){
        try{
            BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
            String line = null;
            while((line=bufr.readLine())!=null){
                byte[] buf = line.getBytes();
                DatagramPacket dp = 
                    new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.255"),10002);
                ds.send(dp);
                if("886".equals(line))
                    break;
            }
        }
        catch (Exception e){
            throw new RuntimeException("发送端失败");
        }
    }
}
class Rece implements Runnable{
    private DatagramSocket ds;
    public Rece(DatagramSocket ds){
        this.ds = ds;
    }
    public void run(){
        try{
            while(true){
                byte[] buf = new byte[1024];
                DatagramPacket dp = new DatagramPacket(buf,buf.length);
 
                ds.receive(dp);
 
 
                String ip = dp.getAddress().getHostAddress();
 
                String data = new String(dp.getData(),0,dp.getLength());
 
                if("886".equals(data)){
                    System.out.println(ip+"....离开聊天室");
                    break;
                }
                System.out.println(ip+":"+data);
            }
        }
        catch (Exception e){
            throw new RuntimeException("接收端失败");
        }
    }
}
 
 
class  ChatDemo{
    public static void main(String[] args) throws Exception{
        DatagramSocket sendSocket = new DatagramSocket();
        DatagramSocket receSocket = new DatagramSocket(10002);
 
        new Thread(new Send(sendSocket)).start();
        new Thread(new Rece(receSocket)).start();
 
    }
}
9,TCP
1,tcp分客户端和服务端。
2,客户端对应的对象是Socket
     服务端对应的对象是ServerSocket
TCP----->客户端
通过查阅socket对象,发现在该对象建立时,就可以去连接指定主机。
因为tcp是面向连接的。所以在建立socket服务时,
就要有服务端存在,并连接成功。形成通路后,在该通道进行数据的传输。
需求:给服务端发送给一个文本数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
步骤:
1,创建Socket服务。并指定要连接的主机和端口
2,为了发送数据,应该获取socket流中的输出流
import java.io.*;
import java.net.*;
class  TcpClient{
    public static void main(String[] args) throws Exception {
        //创建客户端的socket服务。指定目的主机和端口
        Socket s = new Socket("192.168.1.254",10003);
        //为了发送数据,应该获取socket流中的输出流。
        OutputStream out = s.getOutputStream();
        out.write("tcp ge men lai le ".getBytes());
        s.close();
    }
}
TCP---服务端
步骤:
1,建立服务端的socket服务。ServerSocket(); ,并监听一个端口。 
2,获取连接过来的客户端对象。
 通过ServerSokcet的 accept方法。没有连接就会等,所以这个方法阻塞式的。
3,客户端如果发过来数据,那么服务端要使用对应的客户端对象,并获取到该客户端对象的读取流来读取发过来的数据。
 并打印在控制台。
4,关闭服务端(可选)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class  TcpServer{
    public static void main(String[] args) throws Exception{
        //建立服务端socket服务。并监听一个端口。
        ServerSocket ss = new ServerSocket(10003);
        //通过accept方法获取连接过来的客户端对象。
        while(true){
        Socket s = ss.accept();
        String ip = s.getInetAddress().getHostAddress();
        System.out.println(ip+".....connected");
        //获取客户端发送过来的数据,那么要使用客户端对象的读取流来读取数据。
        InputStream in = s.getInputStream();
        byte[] buf = new byte[1024];
        int len = in.read(buf);
        System.out.println(new String(buf,0,len));
        s.close();//关闭客户端.
        }
        //ss.close();
    }
}
10,TCP---客户端和服务端的互访
TCP---客户端
1,建立socket服务。指定要连接主机和端口。
2,获取socket流中的输出流。将数据写到该流中。通过网络发送给服务端。
3,获取socket流中的输入流,将服务端反馈的数据获取到,并打印。
4,关闭客户端资源
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class TcpClient2 {
    public static void main(String[] args)throws Exception {
        Socket s = new Socket("192.168.1.254",10004);
        //发送
        OutputStream out = s.getOutputStream();
        out.write("服务端,你好".getBytes());
        //接收
        InputStream in = s.getInputStream();
        byte[] buf = new byte[1024];
        int len = in.read(buf);
        System.out.println(new String(buf,0,len));
        s.close();
    }
}
TCP----服务端
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class TcpServer2{
    public static void main(String[] args) throws Exception{
        ServerSocket ss = new ServerSocket(10004);
        Socket s = ss.accept();
        String ip = s.getInetAddress().getHostAddress();
        System.out.println(ip+"....connected");
        InputStream in = s.getInputStream();
        byte[] buf = new byte[1024];
        int len = in.read(buf);
        System.out.println(new String(buf,0,len));
        //发送
        OutputStream out = s.getOutputStream();
        Thread.sleep(10000);
        out.write("哥们收到,你也好".getBytes());
        s.close();
        ss.close();
    }
}
11,TCP练习----文本转换器
该例子出现的问题。
现象:客户端和服务端都在莫名的等待。
为什么呢?
因为客户端和服务端都有阻塞式方法。这些方法么没有读到结束标记。那么就一直等
而导致两端,都在等待。
需求:建立一个文本转换服务器。
客户端给服务端发送文本,服务单会将文本转成大写在返回给客户端。
而且客户度可以不断的进行文本转换。当客户端输入over时,转换结束。
分析:
客户端:
既然是操作设备上的数据,那么就可以使用io技术,并按照io的操作规律来思考。
源:键盘录入。
目的:网络设备,网络输出流。
而且操作的是文本数据。可以选择字符流。
步骤
1,建立服务。
2,获取键盘录入。
3,将数据发给服务端。
4,获取服务端返回的大写数据。
5,结束,关资源。
都是文本数据,可以使用字符流进行操作,同时提高效率,加入缓冲。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class  TransClient{
    public static void main(String[] args) throws Exception{
        Socket s = new Socket("192.168.1.254",10005);
        //定义读取键盘数据的流对象。
        BufferedReader bufr = 
            new BufferedReader(new InputStreamReader(System.in));
        //定义目的,将数据写入到socket输出流。发给服务端。
        //BufferedWriter bufOut = 
            //new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        PrintWriter out = new PrintWriter(s.getOutputStream(),true);
        //定义一个socket读取流,读取服务端返回的大写信息。
        BufferedReader bufIn = 
            new BufferedReader(new InputStreamReader(s.getInputStream()));
        String line = null;
        while((line=bufr.readLine())!=null){
            if("over".equals(line))
                break
            out.println(line);
//          bufOut.write(line);
//          bufOut.newLine();
//          bufOut.flush();
            String str =bufIn.readLine();
            System.out.println("server:"+str);     
        }
        bufr.close();
        s.close();
    }
}
服务端
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class  TransServer{
    public static void main(String[] args) throws Exception{
        ServerSocket ss = new ServerSocket(10005);
        Socket s = ss.accept();
        String ip = s.getInetAddress().getHostAddress();
        System.out.println(ip+"....connected");
        //读取socket读取流中的数据。
        BufferedReader bufIn =
            new BufferedReader(new InputStreamReader(s.getInputStream()));
        //目的。socket输出流。将大写数据写入到socket输出流,并发送给客户端。
        //BufferedWriter bufOut = 
            //new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        PrintWriter out = new PrintWriter(s.getOutputStream(),true);
        String line = null;
        while((line=bufIn.readLine())!=null){
            System.out.println(line);
            out.println(line.toUpperCase());
//          bufOut.write(line.toUpperCase());
//          bufOut.newLine();
//          bufOut.flush();
        }
        s.close();
        ss.close();
    }
}
12,TCP练习----复制文件
注意事项:
1,服务器端的readLine( )如何结束循环?
可以自定义循环标记,over或者加入时间,前提是你得让服务器知道这个标记
也可以用shutdownOutput(),用Socket中的方法加入一个结束后标记
2,实际的文件在网络中传输复制是哪样的?
客户端先发给服务端一个要复制的文件的名字,服务端先建立好
然后再传输数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class  TextClient{
    public static void main(String[] args) throws Exception{
        Socket s = new Socket("192.168.1.254",10006);
        BufferedReader bufr = 
            new BufferedReader(new FileReader("IPDemo.java"));
        PrintWriter out = new PrintWriter(s.getOutputStream(),true);
        String line = null;
        while((line=bufr.readLine())!=null){
            out.println(line);
        }
        s.shutdownOutput();//关闭客户端的输出流。相当于给流中加入一个结束标记-1.       
        BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String str = bufIn.readLine();
        System.out.println(str);
        bufr.close();
        s.close();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class  TextServer{
    public static void main(String[] args) throws Exception{
        ServerSocket ss = new ServerSocket(10006);
        Socket s = ss.accept();
        String ip = s.getInetAddress().getHostAddress();
        System.out.println(ip+"....connected");
        BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
        PrintWriter out  = new PrintWriter(new FileWriter("server.txt"),true);
        String line = null;
        while((line=bufIn.readLine())!=null){
            //if("over".equals(line))
                //break;
            out.println(line);
        }
        PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
        pw.println("上传成功");
        out.close();
        s.close();
        ss.close();
    }
}
0 0
原创粉丝点击