一、网络通讯要素。
IP地址:
1.网络中设备的标识。
2.不以记忆,可用主机名。
3.本地网络地址:127.0.0.1 主机名 localhost
端口号:
1.用于标识进程的逻辑地址,不同进程的标识
2.有效端口:0~65535,其中0~1024系统使用或保留的端口。
传输协议:
1.通讯的规则
2.常见的协议: TCP ,UDP,HTTP
UDP:
1.将数据及源和目的封装成数据包中,不需要建立连接。
2.每个数据报的大小在限制在64K内。
3.因无连接,是不可靠协议。
4.不需要建立连接,速度快。
TCP:
1.建立连接,形成传输数据的通道。
2.在连接中进行大数据量传输。
3.通过三次握手完成连接,是可靠协议。
4.必须建立连接,效率会稍低。
二、网络编程。
Socket:
1.Socket就是为网络服务提供的一种机制。
2.通信的两端都有Socket。
3.网络通信其实就是Socket间的通信。
4.数据在两个Socket间通过IO传输。
ServerSocket服务器:
服务器实例:
public class ServerSocketTest{
public static void main(String[] args)throws IOException {
//创建一个Server对象
ServerSocket server=new ServerSocket(12345);//端口号
//调用accept方法,等待在端口上,一直阻塞在这里,直到等到了一个Socket连接到这端口时,得到返回值。
Socket socket=server.accept();
//打印连接上来的Socket的IP地址
System.out.println("ServerSocket得到一个连接"+socket.getInetAddress().toString());
//获取客户端的输出流,并包装到一个BufferWriter
OutputStream os=socket.getOutputStream();
BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(os));
//发送数据
writer.write("嗨,我是服务器!!!");
//关闭流
writer.close();
server.close();
}
}
Socket客户端:
public class SocketTest{
public static void main(String[] args)throws UnknownHostException,IOException{
//创建一个Socket对象,创建时,就会连接到服务器
Socket socket=new Socket("127.0.0.1",12345);//ip地址和端口号
//因为服务器会先发送一个信息到客户端,所以我们先接收数据
InputStream is=socket.getInputStream();
//选择处理流
BufferedReader reader=new BufferedReader(new InputStreamReader(os));
//读取数据
String reStr=reader.readLine();
//关闭输入流
reader.close();
socket.close();
}
}
UDP传输:
1.DatagramSocket与DatagramPacket
2.建立发送端,接收端。
3.建立数据包。
4.调用Socket的发送接收方法。
5.关闭Socket。
实例发送数据包:
public class UDPSend{
public static void main(String[] args){
try {
//创建UDP套接字
DatagramSocket socket=new DatagramSocket();
//创建String类型的数据报
String str="嗨,你好!!!";
//把数据报装入byte[]数组中
byte[] buf=str.getBytes();
//创建发送数据包
DatagramPack p=new DatagramPack(buf.length,InetAddress.getByName("127.0.0.1"),10002);//ip地址和端口号
//等待客户登陆发送数据
socket.send(p);
//关闭
socket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
实例接收数据包:
public class UDPReceive{
public static void main(String[] args){
try {
//创建套接字
DatagramSocket socket=new DatagramSocket(10002);//填入端口号
//创建数据接收包
DatagramPacket p=new DatagramPacket(new byte[1024],1024);
//接收数据包
socket.receive(p);
//打印信息
System.out.println("信息:"+new String(p.getData(),p.getOffset(),p.getLength()));
}catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
URLConnection是一个抽象类,它有两个直接子类分别是HttpURLConnection和JarURLConnection。
另外一重要的的类是URL,通常URL可以通过传给构造器一个String类型的参数来生成一个指向特定地址的URL实例。
访问网络的基本过程:
获取URL对象的属性:
getDefaultPort() //返回默认的端口号。
getFile(); //获得URL指定资源的完整文件名。
getHost(); //返回主机名。
getPath(); //返回指定资源的文件目录和文件名。
getPort(); //返回端口号,默认为-1。
getProtocol(); //返回表示URL中协议的字符串对象。
getRef(); //返回URl中的HTML文档标记,即#号标记。
getUSerInfo(); //返回用户信息。
toString(); //返回完整的URL字符串。
利用HttpURLConnection来服务器互交的基本过程:
1.将访问路径封装成URL对象,通过URL对象获取到HttpRULConnection。
2.设置连接参数。
3.连接到服务器。
4.向服务器写数据(可选)。
5.读取服务器返回的数据。
HttpURLConnection的获取:
HttpURLConnection是java的标准类,继承自URLConnection类,URLConnection不HttpURLConnection都是抽象类,无法直接实例化对象。
其对象主要通过URL的openConnection()方法获得,创建一个httpURLConnection连接的代码如下所示:
–URL url = new UR(“http://www.baidu.com”);
–HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
openConnection()方法只创建URLConnection戒者HttpURLConnection实例,但是并开进行真正的连接操作。
并且,每次openConnection都将创建一个新的实例。因此,在连接乊前我们可以对其一些属性进行设置,比如超时时间等。
设置连接参数:
下面对HttpURLConnetcion实例的属性设置:
//设置输入/输出流
–connection.setDoOutput(true);
–connection.setDoInput(true);
//设置请求的方式为Get戒者Post
–connection.setRequestMethod(“GET”);
–connection.setRequestMethod(“POST”);
//在设置POST方式时要注意,POST请求方式丌能够使用缓存
–connection.setUseCaches(false);
在完成HttpURLConnection实例的初始化以后,我们可以分别使用Get和POST方式来完成一个实例。
实例下载数据:
普通下载:
public class HTTPRequest{
public static void main(){
try {
//创建URL对象
URL url=new URL("下载地址");//www.baidu.con
//建立连接
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
//读取文件
InputStream is=conn.getInputStream();
//保存下载位置
String str="E:/Download.jpeg";
//写文件
FileOutputStream fos=new FileOutputStream(str);
//设置读取数据的大小
byte[] buf=new byte[1024];
//设置实际读取数据大小
int length=0;
//开始下载文件
while((length=is.read(buf))!=-1){
//开始往文件里写入数据
fos.wrtie(buf,0,length);
//刷新管道里的数据
fos.flush();
}
//关闭流
is.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
普通断点下载:
public class HTTPBreakDownload{
public static void main(String[] args){
try {
//创建URL对象
URL url=new URL("下载地址");
//创建连接
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
//找到要继续下载的文件
File flies=new File("E://Download.jpeg");
//获取下载文件的长度
long flieDownloadLength=flies.length();
//设置连接到以前下载的后面
conn.setRequestPropety("Range","bytes="+fileDownLength+"-");
//选择下载流
InputStream is=conn.getInputStream();
//保存下载位置
String str="Download.jpeg";
//建立输出流
//r读 rw读写 rws优化了的读写 rwd(常用)
RandomAccessFile raf=new RandomAccessFile(conn,"rwd");
//偏移量
raf.seek(fileDownloadLength);
//设置读取数据的大小
byte[] buf=new byte[1024];
//获取到实际读取数据的大小
int readLength=0;
//开始读
while((readLength=is.raed(buf))!=-1){
//开始往文件写
raf.write(buf,0,readLength);
}
//关闭流
raf.close();
is.close();
}catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
多线程下载:
public class MultiThreadDownload{
public static void main(String[] args){
//获取下载的数据大小
long dLength=getSize();
//创建线程
int threadNum=3;
//保存平均下载的多余的数据
int lastLength=dLength%threadNum;
//平均下载的数据
long avg=(dLength-lastLength)/threadNum;
//第一根线程的开始下载数据起点
long one=0;
//第二根线程的开始下载数据起点
long two=one+avg;
//第三根线程的开始下载数据起点
long three=two+avg;
//下载文件保存位置
File file=new Fiel("Download.jpeg");
new Thread(new DownloadThread(one,avg,file)).start();
new Thread(new DownloadThread(two,avg,file)).start();
new Thread(new DownloadThread(three,avg+lastLenth,file)).start();
}
//获取下载文件的大小
public static long getSize(){
//创建URL标识符
URL url=null;
//创建对象
HttpURLConnection conn=null;
try {
//创建URL对象
url=new URL("下载地址");
//建立连接
conn=(HttpURLConnection)url.openConnection();
} catch (Exception e) {
e.printStackTrace();
}
//获取下载文件的大小
long flieLength=conn.getContentLength();
return flieLength;
}
}
class DownloadThrad extends Thread{
//下载数据大小
long dLength=0;
//文件保存下载的位置
File file;
//下载开始数据大小
long offset=0;
//获取开始数据大小
}
//设置下载开始数据大小
public void setOffset(long offset){
this.offset=offset;
}
//空构造器
public DownloadThread(){
}
/**
* 有参构造器
* */
public DownloadThread(long offset,long dLength,File file){
this.offset=offset;
this.dLength=dLength;
this.file=file;
}
@Override
public void run(){
//选择输入流
InputStream is=null;
//选择输出流
RandomAccessFile raf=null;
try {
//创建URL对象
URL url=new URL("下载地址");
//与服务器建立连接
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
//获取消息头
conn.setRequestProperty("Range","bytes="+offset+"-"+(offset+dLength));
//获取下载请求
is.getInputStream();
//输出文件
raf.seek(offset);
//设置读取数据大小
byte[] buf=new byte[1024];
//设置实际读取大小
long length=0;
//开始读取数据
while((length=is.read(buf))!=-1){
//开始向文件写入数据
raf.write(buf,0,length);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
IP地址:
1.网络中设备的标识。
2.不以记忆,可用主机名。
3.本地网络地址:127.0.0.1 主机名 localhost
端口号:
1.用于标识进程的逻辑地址,不同进程的标识
2.有效端口:0~65535,其中0~1024系统使用或保留的端口。
传输协议:
1.通讯的规则
2.常见的协议: TCP ,UDP,HTTP
UDP:
1.将数据及源和目的封装成数据包中,不需要建立连接。
2.每个数据报的大小在限制在64K内。
3.因无连接,是不可靠协议。
4.不需要建立连接,速度快。
TCP:
1.建立连接,形成传输数据的通道。
2.在连接中进行大数据量传输。
3.通过三次握手完成连接,是可靠协议。
4.必须建立连接,效率会稍低。
二、网络编程。
Socket:
1.Socket就是为网络服务提供的一种机制。
2.通信的两端都有Socket。
3.网络通信其实就是Socket间的通信。
4.数据在两个Socket间通过IO传输。
ServerSocket服务器:
服务器实例:
public class ServerSocketTest{
public static void main(String[] args)throws IOException {
//创建一个Server对象
ServerSocket server=new ServerSocket(12345);//端口号
//调用accept方法,等待在端口上,一直阻塞在这里,直到等到了一个Socket连接到这端口时,得到返回值。
Socket socket=server.accept();
//打印连接上来的Socket的IP地址
System.out.println("ServerSocket得到一个连接"+socket.getInetAddress().toString());
//获取客户端的输出流,并包装到一个BufferWriter
OutputStream os=socket.getOutputStream();
BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(os));
//发送数据
writer.write("嗨,我是服务器!!!");
//关闭流
writer.close();
server.close();
}
}
Socket客户端:
public class SocketTest{
public static void main(String[] args)throws UnknownHostException,IOException{
//创建一个Socket对象,创建时,就会连接到服务器
Socket socket=new Socket("127.0.0.1",12345);//ip地址和端口号
//因为服务器会先发送一个信息到客户端,所以我们先接收数据
InputStream is=socket.getInputStream();
//选择处理流
BufferedReader reader=new BufferedReader(new InputStreamReader(os));
//读取数据
String reStr=reader.readLine();
//关闭输入流
reader.close();
socket.close();
}
}
UDP传输:
1.DatagramSocket与DatagramPacket
2.建立发送端,接收端。
3.建立数据包。
4.调用Socket的发送接收方法。
5.关闭Socket。
实例发送数据包:
public class UDPSend{
public static void main(String[] args){
try {
//创建UDP套接字
DatagramSocket socket=new DatagramSocket();
//创建String类型的数据报
String str="嗨,你好!!!";
//把数据报装入byte[]数组中
byte[] buf=str.getBytes();
//创建发送数据包
DatagramPack p=new DatagramPack(buf.length,InetAddress.getByName("127.0.0.1"),10002);//ip地址和端口号
//等待客户登陆发送数据
socket.send(p);
//关闭
socket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
实例接收数据包:
public class UDPReceive{
public static void main(String[] args){
try {
//创建套接字
DatagramSocket socket=new DatagramSocket(10002);//填入端口号
//创建数据接收包
DatagramPacket p=new DatagramPacket(new byte[1024],1024);
//接收数据包
socket.receive(p);
//打印信息
System.out.println("信息:"+new String(p.getData(),p.getOffset(),p.getLength()));
}catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
URLConnection是一个抽象类,它有两个直接子类分别是HttpURLConnection和JarURLConnection。
另外一重要的的类是URL,通常URL可以通过传给构造器一个String类型的参数来生成一个指向特定地址的URL实例。
访问网络的基本过程:
获取URL对象的属性:
getDefaultPort() //返回默认的端口号。
getFile(); //获得URL指定资源的完整文件名。
getHost(); //返回主机名。
getPath(); //返回指定资源的文件目录和文件名。
getPort(); //返回端口号,默认为-1。
getProtocol(); //返回表示URL中协议的字符串对象。
getRef(); //返回URl中的HTML文档标记,即#号标记。
getUSerInfo(); //返回用户信息。
toString(); //返回完整的URL字符串。
利用HttpURLConnection来服务器互交的基本过程:
1.将访问路径封装成URL对象,通过URL对象获取到HttpRULConnection。
2.设置连接参数。
3.连接到服务器。
4.向服务器写数据(可选)。
5.读取服务器返回的数据。
HttpURLConnection的获取:
HttpURLConnection是java的标准类,继承自URLConnection类,URLConnection不HttpURLConnection都是抽象类,无法直接实例化对象。
其对象主要通过URL的openConnection()方法获得,创建一个httpURLConnection连接的代码如下所示:
–URL url = new UR(“http://www.baidu.com”);
–HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
openConnection()方法只创建URLConnection戒者HttpURLConnection实例,但是并开进行真正的连接操作。
并且,每次openConnection都将创建一个新的实例。因此,在连接乊前我们可以对其一些属性进行设置,比如超时时间等。
设置连接参数:
下面对HttpURLConnetcion实例的属性设置:
//设置输入/输出流
–connection.setDoOutput(true);
–connection.setDoInput(true);
//设置请求的方式为Get戒者Post
–connection.setRequestMethod(“GET”);
–connection.setRequestMethod(“POST”);
//在设置POST方式时要注意,POST请求方式丌能够使用缓存
–connection.setUseCaches(false);
在完成HttpURLConnection实例的初始化以后,我们可以分别使用Get和POST方式来完成一个实例。
实例下载数据:
普通下载:
public class HTTPRequest{
public static void main(){
try {
//创建URL对象
URL url=new URL("下载地址");//www.baidu.con
//建立连接
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
//读取文件
InputStream is=conn.getInputStream();
//保存下载位置
String str="E:/Download.jpeg";
//写文件
FileOutputStream fos=new FileOutputStream(str);
//设置读取数据的大小
byte[] buf=new byte[1024];
//设置实际读取数据大小
int length=0;
//开始下载文件
while((length=is.read(buf))!=-1){
//开始往文件里写入数据
fos.wrtie(buf,0,length);
//刷新管道里的数据
fos.flush();
}
//关闭流
is.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
普通断点下载:
public class HTTPBreakDownload{
public static void main(String[] args){
try {
//创建URL对象
URL url=new URL("下载地址");
//创建连接
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
//找到要继续下载的文件
File flies=new File("E://Download.jpeg");
//获取下载文件的长度
long flieDownloadLength=flies.length();
//设置连接到以前下载的后面
conn.setRequestPropety("Range","bytes="+fileDownLength+"-");
//选择下载流
InputStream is=conn.getInputStream();
//保存下载位置
String str="Download.jpeg";
//建立输出流
//r读 rw读写 rws优化了的读写 rwd(常用)
RandomAccessFile raf=new RandomAccessFile(conn,"rwd");
//偏移量
raf.seek(fileDownloadLength);
//设置读取数据的大小
byte[] buf=new byte[1024];
//获取到实际读取数据的大小
int readLength=0;
//开始读
while((readLength=is.raed(buf))!=-1){
//开始往文件写
raf.write(buf,0,readLength);
}
//关闭流
raf.close();
is.close();
}catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
多线程下载:
public class MultiThreadDownload{
public static void main(String[] args){
//获取下载的数据大小
long dLength=getSize();
//创建线程
int threadNum=3;
//保存平均下载的多余的数据
int lastLength=dLength%threadNum;
//平均下载的数据
long avg=(dLength-lastLength)/threadNum;
//第一根线程的开始下载数据起点
long one=0;
//第二根线程的开始下载数据起点
long two=one+avg;
//第三根线程的开始下载数据起点
long three=two+avg;
//下载文件保存位置
File file=new Fiel("Download.jpeg");
new Thread(new DownloadThread(one,avg,file)).start();
new Thread(new DownloadThread(two,avg,file)).start();
new Thread(new DownloadThread(three,avg+lastLenth,file)).start();
}
//获取下载文件的大小
public static long getSize(){
//创建URL标识符
URL url=null;
//创建对象
HttpURLConnection conn=null;
try {
//创建URL对象
url=new URL("下载地址");
//建立连接
conn=(HttpURLConnection)url.openConnection();
} catch (Exception e) {
e.printStackTrace();
}
//获取下载文件的大小
long flieLength=conn.getContentLength();
return flieLength;
}
}
class DownloadThrad extends Thread{
//下载数据大小
long dLength=0;
//文件保存下载的位置
File file;
//下载开始数据大小
long offset=0;
//获取开始数据大小
public long getOffset(){
return offset;}
//设置下载开始数据大小
public void setOffset(long offset){
this.offset=offset;
}
//空构造器
public DownloadThread(){
}
/**
* 有参构造器
* */
public DownloadThread(long offset,long dLength,File file){
this.offset=offset;
this.dLength=dLength;
this.file=file;
}
@Override
public void run(){
//选择输入流
InputStream is=null;
//选择输出流
RandomAccessFile raf=null;
try {
//创建URL对象
URL url=new URL("下载地址");
//与服务器建立连接
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
//获取消息头
conn.setRequestProperty("Range","bytes="+offset+"-"+(offset+dLength));
//获取下载请求
is.getInputStream();
//输出文件
raf.seek(offset);
//设置读取数据大小
byte[] buf=new byte[1024];
//设置实际读取大小
long length=0;
//开始读取数据
while((length=is.read(buf))!=-1){
//开始向文件写入数据
raf.write(buf,0,length);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}