欢迎来到 IT实训基地-南通科迅教育
咨询电话:0513-81107100
JAVA之网络编程
2017/4/10
南通科迅教育
646
南通Web前端培训学校哪里好

就是两个(或多个)设备(例如计算机)之间的数据传输。
一、网络:将不同区域的计算机连接到一起 局域网 城域网 互联网
**二、地址:**IP地址 确定网络上 一个绝对地址 |位置 —>房子的地址
三、端口号: 区分计算机软件的 –>房子的房门 2个字节 0-65535 共65536个
1、在同一个协议下 端口号不能重复 不同协议下可以重复
2、1024以下的不要使用 80–>http 21 –>ftp
四、资源定位: URL 统一资源定位符 URI :统一资源
五、数据的传输
1、协议: Tcp 和UDP协议
1)、TCP(transfer control protocol): 电话 类似于三次握手 面向连接 安全可靠 效率低下
2)、UDP(UserDatagramProtocol ): 短信 非面向连接 效率高
2、传输:
1)、先封装
2)、后拆封

编程相关类">网络编程相关类

1、InetAddress InetSocketAddress
2、URL
3、TCP: ServerSocket Socket
4、UDP: DatagramSocket DatagramPacket

InetAddress

封装计算机的IP地址和DNS。无端口。

方法:
getHostAddress():返回IP地址
getHostName():返回域名/本机为计算机名
InetAddress.getLocalHost():返回本机IP,如果IP不存在则返回自身
InetAddress.getByName(“IP地址/域名”):根据IP地址/域名得到InetAddress对象。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
publicstaticvoidmain(String[] args)throwsUnknownHostException{    
    //使用getLocalHost方法创建InetAddress对象
    InetAddress addr = InetAddress.getLocalHost();
    System.out.println(addr.getHostAddress()); //返回:192.168.1.100
    System.out.println(addr.getHostName()); //输出计算机名
    //根据域名得到InetAddress对象
    addr = InetAddress.getByName("www.163.com");
    System.out.println(addr.getHostAddress()); //返回 163服务器的ip:61.135.253.15
    System.out.println(addr.getHostName()); //输出:www.163.com  
    //根据ip得到InetAddress对象
    addr = InetAddress.getByName("61.135.253.15");
    System.out.println(addr.getHostAddress()); //返回 163服务器的ip:61.135.253.15
    System.out.println(addr.getHostName()); //输出ip而不是域名。如果这个IP地 址不存在或DNS服务器不允许进行IP地址和域名的映射,getHostName方法就直接返回这个IP地址。      
 
}

InetSocketAddress

在InetAddress基础上+封装端口。
(1)创建对象
InetSocketAddress(String hostName,int port);
InetSocketAddress(InetAddress addr,int port);
(2)方法
getAddress():返回一个InetAddress对象
getHostName():返回地址
getPort():返回端口

?
1
2
3
4
5
6
7
8
9
publicstaticvoidmain(String[] args)throwsUnknownHostException {
        InetSocketAddress  address =newInetSocketAddress("127.0.0.1",8888);
        address =newInetSocketAddress(InetAddress.getByName("127.0.0.1"),8888);
        System.out.println(address.getHostName());
        System.out.println(address.getPort());
        InetAddress addr =address.getAddress();
        System.out.println(addr.getHostAddress());
        System.out.println(addr.getHostName()); 
    }

URL

URL:统一资源定位符
URI:统一资源标识符

四部分组成:协议 存放协议的主机域名 端口 资源文件名

1.创建
URL(String spec):绝对路径创建
URL(URL url,String a):相对路径创建
2.方法
getProtocol():获取协议
getHost():获取域名
getPort():获取端口
getFile():获取资源
getPath():获取相对路径
getRef():获取锚点(也称为引用)
getQuery():获取参数 在URL路径的?后面
getFile():获取URL文件名部分
getAuthority():获取此URL的授权部分
getDefaultPort():获取协议的默认端口号

?
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
importjava.net.*;
importjava.io.*;
 
publicclassTestURL
{
   publicstaticvoidmain(String [] args)
   {    
    URL url;
    try{
        url =newURL("http://www.baidu.com:80/index.html?uname=vvvvvv#123");
        System.out.println("协议:"+url.getProtocol());
        System.out.println("授权部分:"+url.getAuthority());
        System.out.println("域名:"+url.getHost());
        System.out.println("默认端口:"+url.getDefaultPort());
        System.out.println("端口:"+url.getPort());
        System.out.println("资源:"+url.getFile());
        System.out.println("相对路径:"+url.getPath());
        System.out.println("锚点:"+url.getRef());//锚点
        System.out.println("参数:"+url.getQuery());
    }catch(MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
   }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
//结果
 
协议:http
授权部分:www.baidu.com:80
域名:www.baidu.com
默认端口:80
端口:80
主机:www.baidu.com
资源:/index.html?uname=vvvvvv
相对路径:/index.html
锚点:123
参数:uname=vvvvvv

3.流
InputStream openStream():获取资源网络流

?
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
//网络爬虫原理
 
importjava.io.BufferedReader;
importjava.io.BufferedWriter;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStreamWriter;
importjava.net.URL;
 
publicclassTestURLDemo {
 
    publicstaticvoidmain(String[] args)throwsIOException {
        URL url =newURL("http://www.baidu.com"); // 主页 默认资源
 
        // 获取资源 网络流
/*
        InputStream is = url.openStream();
        byte[] flush = new byte[1024];
        int len = 0;
        while (-1 != (len = is.read(flush))) {
            System.out.println(new String(flush, 0, len));
        }
        is.close();
*/
        BufferedReader br =newBufferedReader(newInputStreamReader(url.openStream(),"utf-8"));
        BufferedWriter bw =newBufferedWriter(newOutputStreamWriter(newFileOutputStream("baidu2.html"),"utf-8"));
 
        String msg =null;
        while((msg = br.readLine()) !=null) {
            // System.out.println(msg);
            bw.append(msg);
            bw.newLine();
        }
        bw.flush();
 
        bw.close();
        br.close();
 
    }
 
}

UDP

1.类 DatagramSocket DatagramPacket
①客户端
(1)创建客户端 DatagramSocket类+指定端口
(2)准备数据 字节数组
(3)打包 DatagramPacket + 服务器地址及端口
(4)发送
(5)释放资源
②服务器端
(1)创建服务器端 DatagramSocket类+指定端口
(2)准备接收容器 字符数组封装DatagramPacket类
(3)包 接受数据
(4)分析
(5)释放资源

PS:服务器需要先创建,否则会引发客户端找不到服务器的问题

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//服务器端
publicclassMyServer {
 
    publicstaticvoidmain(String[] args)throwsIOException {
        //1、创建服务端 +端口
        DatagramSocket server =newDatagramSocket(8888);
        //2、准备接受容器
        byte[] container =newbyte[1024];
        //3、封装成 包 DatagramPacket(byte[] buf, int length)       
        DatagramPacket packet =newDatagramPacket(container, container.length) ;
        //4、接受数据
        server.receive(packet);
        //5、分析数据
        byte[] data =packet.getData();
        intlen =packet.getLength();
        System.out.println(newString(data,0,len));
        //6、释放
        server.close();
 
    }
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//客户端
publicclassMyClient {
 
    publicstaticvoidmain(String[] args)throwsIOException {
        //1、创建客户端 +端口
        DatagramSocket client =newDatagramSocket(6666);
        //2、准备数据
        String msg ="udp编程";
        byte[] data =msg.getBytes();
        //3、打包(发送的地点 及端口) DatagramPacket(byte[] buf, int length, InetAddress address, int port)
        DatagramPacket packet =newDatagramPacket(data,data.length,newInetSocketAddress("localhost",8888));
        //4、发送
        client.send(packet);
        //5、释放
        client.close();
 
    }

//传递除了字符数组以外的东西,需要结合IO流

?
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
publicclassServer {
 
    publicstaticvoidmain(String[] args)throwsIOException {
        //1、创建服务端 +端口
        DatagramSocket server =newDatagramSocket(8888);
        //2、准备接受容器
        byte[] container =newbyte[1024];
        //3、封装成 包 DatagramPacket(byte[] buf, int length)       
        DatagramPacket packet =newDatagramPacket(container, container.length) ;
        //4、接受数据
        server.receive(packet);
        //5、分析数据
        doubledata =convert(packet.getData());
        System.out.println(data);
        //6、释放
        server.close();
 
    }
    /**
     * 字节数组 +Data 输入流
     * @param data
     * @return
     * @throws IOException
     */
    publicstaticdoubleconvert(byte[] data)throwsIOException{
        DataInputStream dis =newDataInputStream(newByteArrayInputStream(data));
        doublenum =dis.readDouble();
        dis.close();
        returnnum;
    }
}
?
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
publicclassClient {
 
    /**
     * @param args
     * @throws IOException
     */
    publicstaticvoidmain(String[] args)throwsIOException {
        //1、创建客户端 +端口
        DatagramSocket client =newDatagramSocket(6666);
        //2、准备数据
        doublenum =89.12;
        byte[] data =convert(num);
        //3、打包(发送的地点 及端口) DatagramPacket(byte[] buf, int length, InetAddress address, int port)
        DatagramPacket packet =newDatagramPacket(data,data.length,newInetSocketAddress("localhost",8888));
        //4、发送
        client.send(packet);
        //5、释放
        client.close();
 
    }
 
    /**
     * 字节数组 数据源  +Data 输出流
     * @param num
     * @return
     * @throws IOException
     */
    publicstaticbyte[] convert(doublenum)throwsIOException{
        byte[] data =null;
        ByteArrayOutputStream bos =newByteArrayOutputStream();
        DataOutputStream dos =newDataOutputStream(bos);
        dos.writeDouble(num);
        dos.flush();
 
        //获取数据
        data = bos.toByteArray();
        dos.close();       
        returndata;
 
    }
}

TCP

面向连接。
1.Socket编程
①服务器端 ServerSocket
(1)创建服务器端 指定端口 ServerSocket(int port)
(2)接受客户端连接 阻塞式Socketaccept()
(3)发送数据 + 接收数据

②客户端
(1)创建客户端 Socket(String host,int port);必须指定服务器+端口,此时就在进行连接
(2)接收数据 + 发送数据
BufferedReader br = new BufferedReader(
new InputStreamReader(
client.getInputStream()));

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
publicclassServer {
 
    publicstaticvoidmain(String[] args)throwsIOException {
        //1、创建服务器  指定端口   ServerSocket(int port)
        ServerSocket server =newServerSocket(8888);
        //2、接收客户端连接   阻塞式
        Socket socket =server.accept();
        System.out.println("一个客户端建立连接");
        //3、发送数据
        String msg ="欢迎使用";
        //输出流
        DataOutputStream dos =newDataOutputStream(socket.getOutputStream());
        dos.writeUTF(msg);
        dos.flush();
 
    }
 
}
?
1
2
3
4
5
6
7
8
9
10
11
12
publicclassClient {
 
    publicstaticvoidmain(String[] args)throwsUnknownHostException, IOException {
        //1、创建客户端   必须指定服务器+端口    此时就在连接
        Socket client =newSocket("localhost",8888);
        //2、接收数据
        DataInputStream dis =newDataInputStream(client.getInputStream());
        String echo = dis.readUTF();
        System.out.println(echo);
    }
 
}

简易聊天室 存在bug
实现群聊私聊功能。

?
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
//client
packagecom.vvvvvv.chatdemo03;
 
importjava.io.BufferedReader;
importjava.io.DataInputStream;
importjava.io.DataOutputStream;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.net.Socket;
importjava.net.UnknownHostException;
 
/**
 * 创建客户端:发送数据+接受数据
 * 写出数据:输出流
 * 读取数据:输入流
 * @author Administrator
 *
 */
publicclassClient  {
    publicstaticvoidmain(String[] args)throwsUnknownHostException, IOException {
        Socket client =newSocket("localhost",8888);
        System.out.println("请输入姓名:");
        BufferedReader br =newBufferedReader(newInputStreamReader(System.in));
        String name = br.readLine();
        if(name.equals(""))
            return;
        //启动线程
        newThread(newSend(client,name)).start();
        newThread(newReceive(client)).start();
    }
}
?
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
//server
packagecom.vvvvvv.chatdemo03;
 
importjava.io.DataInputStream;
importjava.io.DataOutputStream;
importjava.io.IOException;
importjava.net.ServerSocket;
importjava.net.Socket;
importjava.util.ArrayList;
importjava.util.List;
 
importcom.vvvvvv.chatdemo02.CloseUtil;
 
/**
 * 创建服务器
 *
 * @author Administrator
 *
 */
publicclassServer {
 
    privateList<mychannel> all =newArrayList<mychannel>();
 
    publicstaticvoidmain(String[] args)throwsIOException {
        newServer().start();//一个线程代表一个客户端
    }
 
    //启动线程
    publicvoidstart()throwsIOException {
        ServerSocket server =newServerSocket(8888);
        while(true) {
            Socket client = server.accept();
            MyChannel channel =newMyChannel(client);
            all.add(channel);
            newThread(channel).start();
        }
    }
 
    classMyChannelimplementsRunnable {
        privateDataInputStream dis;
        privateDataOutputStream dos;
        privatebooleanisRunning =true;
        privateString name;
 
        publicMyChannel() {
 
        }
 
        publicMyChannel(Socket client) {
            try{
                dis =newDataInputStream(client.getInputStream());
                dos =newDataOutputStream(client.getOutputStream());
                this.name = dis.readUTF();
                this.send("欢迎加入聊天室");
                sendOthers(this.name +"进入了聊天室",true);
 
            }catch(IOException e) {
                // e.printStackTrace();
                isRunning =false;
                CloseUtil.closeAll(dis, dos);
            }
        }
        //发送数据给其他人
        //并且做判断是系统信息还是非系统信息 是私聊还是群聊
        //私聊格式:@name:context
 
        publicvoidsendOthers(String msg,booleanflag) {
            if(msg.startsWith("@") && msg.indexOf(":") > -1) {
                String name = msg.substring(1, msg.indexOf(":"));
                String context = msg.substring(msg.indexOf(":") +1);
                for(MyChannel temp:all) {
                    if(temp.name.equals(name)) {
                        temp.send(this.name+"悄悄地对你说:"+context);
                    }
                }
 
            }else{
                for(MyChannel temp : all) {
                    if(temp ==this) {
                        continue;
                    }
                    if(flag)
                        temp.send("系统消息:"+ msg);
                    else
                        temp.send(this.name +"对所有人说:"+msg);
                }
            }
        }
        //将msg发送出去 谁调用就发送给谁
        publicvoidsend(String msg) {
            if(null!= msg && !msg.equals("")) {
                try{
                    dos.writeUTF(msg);
                    dos.flush();
                }catch(IOException e) {
                    // e.printStackTrace();
                    isRunning =false;
                    CloseUtil.closeAll(dos);
                    all.remove(this);
                }
            }
        }
        //接收数据
        publicString receive() {
            String msg ="";
            try{
                msg = dis.readUTF();
            }catch(IOException e) {
                isRunning =false;
                CloseUtil.closeAll(dis);
                all.remove(this);
            }
            returnmsg;
        }
 
        @Override
        publicvoidrun() {
            //线程体
            while(isRunning) {
                sendOthers(this.receive(),false);
            }
 
        }
    }
}
</mychannel></mychannel>
?
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
//客户端发送数据线程
packagecom.vvvvvv.chatdemo03;
 
importjava.io.BufferedReader;
importjava.io.DataOutputStream;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.net.Socket;
 
/**
 * 发送数据线程
 * @author Administrator
 *
 */
publicclassSendimplementsRunnable {
 
    //控制台输入流
    privateBufferedReader console;
    //输出流
    privateDataOutputStream dos;
    //线程标识
    privatebooleanisRunning =true;
    //当前线程
    privateString name;
 
    publicSend() {
        console =newBufferedReader(newInputStreamReader(System.in));
    }
    publicSend(Socket client,String name) {
        this();
        try{
            dos =newDataOutputStream(client.getOutputStream());
            this.name = name;
            send(this.name);
        }catch(IOException e) {
            isRunning =false;
            CloseUtil.closeAll(dos,console);
        }
    }
    privateString getMsgFromConsole() {
        try{
            returnconsole.readLine();
        }catch(IOException e) {
        }
        return"";
    }
    /**
     * 从控制台接收数据
     * 发送数据
     */
    publicvoidsend (String msg) {
        if(null!= msg &&  !msg.equals("")) {
            try{
                dos.writeUTF(msg);
                dos.flush();
            }catch(IOException e) {
                isRunning =false;
                CloseUtil.closeAll(dos,console);
            }
        }
    }
    publicvoidrun() {
        while(isRunning)
            send(getMsgFromConsole());
    }
 
}
?
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
//客户端接收数据线程
packagecom.vvvvvv.chatdemo03;
 
importjava.io.DataInputStream;
importjava.io.IOException;
importjava.net.Socket;
 
/**
 * 接收数据线程
 * @author Administrator
 *
 */
publicclassReceiveimplementsRunnable {
 
    privateDataInputStream dis;
    privatebooleanisRunning =true;
    publicReceive() {
 
    }
 
    publicReceive(Socket client) {
        try{
            dis =newDataInputStream(client.getInputStream());
        }catch(IOException e) {
            isRunning =false;
            CloseUtil.closeAll(dis);
        }
    }
 
    publicString receive() {
        String msg ="";
        try{
            msg = dis.readUTF();
        }catch(IOException e) {
            isRunning =false;
            CloseUtil.closeAll(dis);
        }
        returnmsg;
    }
    publicvoidrun() {
        while(isRunning)
            System.out.println(receive());
    }
 
}
?
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
//关闭流工具类
packagecom.vvvvvv.chatdemo03;
 
importjava.io.Closeable;
importjava.io.IOException;
 
/**
 * 关闭流的方法
 * @author Administrator
 *
 */
 
publicclassCloseUtil {
 
    publicstaticvoidcloseAll(Closeable... io) {
        for(Closeable temp: io) {
            if(null!= temp) {
                try{
                    temp.close();
                }catch(IOException e) {
 
                }
            }
        }
    }
}
77
关闭
先学习,后交费申请表
每期5位名额
在线咨询
免费电话
QQ联系
先学习,后交费
TOP
您好,您想咨询哪门课程呢?
关于我们
机构简介
官方资讯
地理位置
联系我们
0513-91107100
周一至周六     8:30-21:00
微信扫我送教程
手机端访问
南通科迅教育信息咨询有限公司     苏ICP备15009282号     联系地址:江苏省南通市人民中路23-6号新亚大厦三楼             法律顾问:江苏瑞慈律师事务所     Copyright 2008-