网络编程
1.IP地址
IP:
定义网络上的节点,节点的地址,手机,ipad,电脑,服务器...
IPV4 ,IPV6
127.0.0.1 本机IP
localhost 域名
192.168.0.0 ~192.168.255.255 非注册ip ,共组织使用的私人IP
net 包
InetAddress 表示网络中的ip
public class NetDemo02 {
public static void main(String[] args) throws UnknownHostException {
//static InetAddress getByName(String host)
//决定了IP地址的主机,主机的名字。
//static InetAddress getLocalHost()
InetAddress ip1 = InetAddress.getLocalHost();//返回本地主机的地址。
InetAddress ip2 = InetAddress.getByName("www.shsxt.com");//返回网站的地址
System.out.println(ip2); //DESKTOP-P04TCL5/192.168.4.154 www.shsxt.com/123.56.138.186
//getHostName()
//这个IP地址的主机名。
System.out.println(ip2.getHostAddress()); //123.56.138.186
System.out.println(ip2.getHostName());
}
}2.端口
端口 : 区分软件
0~65535 2个字节
注意:
统一协议下端口号不能冲突
建议使用8000以上的端口号,8000以内成为预留端口号
常见 端口号:
80 http
8080 tomcat
3306 mysql
1521 oracle
InetSocketAddress : 这个类实现了一个IP套接字地址(IP地址+端口号)
public class PortDemo03 {
public static void main(String[] args) {
//InetSocketAddress(String hostname, int port)
//创建一个套接字地址的主机名和端口号。
InetSocketAddress address = new InetSocketAddress("127.0.0.1",8888);
System.out.println(address);
//getHostName()
//getPort()
System.out.println(address.getHostString());
System.out.println(address.getAddress());
System.out.println(address.getPort());
}
}3.URL
URL : 统一资源定位符
是互联网的三大基石之一: html http url
协议 域名 端口 资源 http://www.baidu.com:80/index.html?uname=zhangsan&pwd=123#a URL : 类 URL代表一个统一资源定位符,一个指向万维网上的“资源”。
protocol://userInfo@host:port/path?query#fragment
协议://用户信息@主机名:端口/路径?查询#锚点
public class URLDemo04 {
public static void main(String[] args) throws MalformedURLException {
//URL(String spec)
URL url = new URL("http://www.baidu.com:80/index.html?uname=zhangsan&pwd=123#a");
System.out.println(url);
System.out.println("协议:"+url.getProtocol());
System.out.println("域名:"+url.getHost());
System.out.println("端口:"+url.getPort());
System.out.println("资源1:"+url.getFile());
System.out.println("资源2:"+url.getPath());
System.out.println("数据:"+url.getQuery());
System.out.println("锚点:"+url.getRef());
}
}4.爬虫
爬虫:
URL :
数据读入到程序中,写出到本地baidu.html
public class SpiderDemo05 {
public static void main(String[] args) throws IOException {
URL url = new URL("http://www.baidu.com");
//InputStream openStream()
BufferedReader rd = new BufferedReader(new InputStreamReader(url.openStream()));
String msg = null;
while((msg=rd.readLine())!=null){
System.out.println(msg);
}
rd.close();
}
}5.UDP与TCP
5.1传输层协议
TCP:TCP(transfer control protocol) 打电话 面向连接、安全、可靠,效率低
UDP:UDP(UserDatagramProtocol ) 发送短信 非面向连接、不安全、数据可能丢失 、效率高
5.2UDP编程
UserDatagramProtocol,一种无连接的传输层协议,提供面向事务的简单不可靠信息传送服务。其特点为:非面向连接;传输不可靠;数据可能丢失。
服务器端:
①创建服务器 DatagramSocket类 +指定端口 (定义服务器端的监听端口)
②准备接收容器 字节数组 +封装成DatagramPacket数据报 (准备容器接收数据)
③接收数据
④分析数据
⑤释放资源
客户端:
①创建客户端 DatagramSocket类 +指定端口 (定义客户端的监听端口)
②准备数据 字节数组
③封装成数据包 需要指定包发送的地址+端口 即服务器地与端口 (打包要发送的数据)
④发送数据
⑤释放资源
注意:只有先运行服务器端,才能接收到数据
字符串的传输:
public class UDPSend01 {
public static void main(String[] args) throws Exception {
//1.定义我是发送端 DatagramSocket(int port)
DatagramSocket send = new DatagramSocket(8888);//客户端
System.out.println("我是发送端...");
//2.准备数据
String str = "发发发";
byte[] bytes = str.getBytes();
//3.打包
DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length,new InetSocketAddress("127.0.0.1",9999));
第一个是要打包的数据,第二个是偏移量,第三个是打包的长度,第四个是打包到哪个端口去
//4.发送
send.send(packet);
//5.关闭
send.close();
}
public class UDPReceive02 {
public static void main(String[] args) throws Exception {
//1.定义我是接收端
DatagramSocket rec = new DatagramSocket(9999);
System.out.println("我是接收端....");
// 2.准备包裹,用来接收数据
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes,bytes.length);
将打包到的数据存到哪
// 3.接收
rec.receive(packet);
// 4.处理数据
//getData() getLength()
byte[] arr = packet.getData();
int len = packet.getLength();
System.out.println(new String(arr,0,len));
// 5.关闭
rec.close();
}
}文件传输:
public class UDPCopyFileClient03 {
public static void main(String[] args) throws Exception {
//1.定义我发送端
DatagramSocket client = new DatagramSocket(7890);
System.out.println("-------------------发送端-------------------");
//2.准备数据
//1) 准备文件字节输入流
InputStream is = new BufferedInputStream(new FileInputStream("D:/test.txt"));
byte[] car = new byte[1024*60];
int len = -1;
//2)读入数据到字节数组
len = is.read(car);
//3.把字节数组打包
DatagramPacket packet = new DatagramPacket(car,0,len,InetAddress.getLocalHost(),9999);
//4.发送
client.send(packet);
//5.关闭
is.close();
client.close();
}
}
public class UDPCopyFileServer04 {
public static void main(String[] args) throws Exception {
//1.定义我是接收端
DatagramSocket server = new DatagramSocket(9999);
System.out.println("-------------------接收端-------------------");
//2.准备包裹接收数据
byte[] car = new byte[10];
DatagramPacket packet = new DatagramPacket(car,car.length);
//3.接收
server.receive(packet);
//4.处理数据
//1).从包裹获取接收的数据
byte[] arr = packet.getData();
int len = packet.getLength();
//2)定义输出流
OutputStream os = new BufferedOutputStream(new FileOutputStream("D:/copy.txt"));
//3).写出到文件中
os.write(arr,0,len);
//4).刷出
os.flush();
//5.关闭
os.close();
server.close();
}
}5.3 TCP编程
Socket:发送 TCP 消息
①连接服务器: 创建客户端 +指定服务器地址 +端口创建客户机Socket,并设置服务器的ip及端口,客户机发出连接请求,建立连接。
②发送数据
通过Socket发送数据,和接收数据
ServerSocket:创建服务器
①创建服务器 指定端口创建服务器ServerSocket,在创建时,定义ServerSocket的监听端口(在这个端口接收客户端发来的消息!)
②等待客户端连接 ServerSocket调用accept()方法,使之处于阻塞状态
③分析接收数据 利用Socket进行接收和发送数据
例:
tcp实现: 客户端
1.定义我是一个客户端 Socket
2.通过IO操作发送数据
3.刷出
4.关闭
public class TCPClient01 {
public static void main(String[] args) throws Exception {
//1.定义我是一个客户端 Socket
Socket client = new Socket("localhost",9999);
System.out.println("------------------Client--------------");
//2.获取输出流 getOutputStream()
DataOutputStream os = new DataOutputStream(new BufferedOutputStream(client.getOutputStream()));
//3.写出字符串
os.writeUTF("哈哈哈");
//4.刷出
os.flush();
//5.关闭
os.close();
client.close();
}
}
tcp实现: 服务器端
1.定义我是服务端 ServerSocket ServerSocket(int port) 创建一个服务器套接字绑定到指定端口。
2.阻塞式监听 Socket accept() 监听连接套接字并接受它。
3.通过IO读入数据
4.处理数据
5.关闭
public class TCPServer02 {
public static void main(String[] args) throws Exception {
//1.定义我是服务端
ServerSocket server = new ServerSocket(9999);
System.out.println("--------------Server-----------------");
//2.阻塞式监听
Socket client = server.accept();
System.out.println("一个客户端已经连接成功....");
//3.获取输入流
DataInputStream is = new DataInputStream(new BufferedInputStream(client.getInputStream()));
//4.读入 数据
String msg = is.readUTF();
System.out.println(msg);
//5.关闭
is.close();
client.close();
server.close();
}
}注意:先运行服务器端,在运行客户端。如果先运行客户端,会出现连接拒绝的异常。
例:TCP实现简单的登录验证
public class TCPLoginClient01 {
public static void main(String[] args) throws Exception {
//1.定义我是一个客户端 Socket
Socket client = new Socket("localhost",9999);
System.out.println("------------------Client--------------");
/*
接收用户键盘输入的用户名与密码
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入用户名:");
String name = reader.readLine();
System.out.println("请输入密码:");
String pwd = reader.readLine();
//2.获取输出流 getOutputStream()
DataOutputStream os = new DataOutputStream(new BufferedOutputStream(client.getOutputStream()));
//3.写出字符串
os.writeUTF("username="+name+"&password="+pwd);
//4.刷出
os.flush();
//5.接收服务器端给响应
DataInputStream is = new DataInputStream(new BufferedInputStream(client.getInputStream()));
System.out.println(is.readUTF());
//6.关闭
os.close();
client.close();
}
}
public class TCPLoginServer02 {
public static void main(String[] args) throws Exception {
//1.定义我是服务端
ServerSocket server = new ServerSocket(9999);
System.out.println("--------------Server-----------------");
//2.阻塞式监听
Socket client = server.accept();
System.out.println("一个客户端已经连接成功....");
//3.获取输入流
DataInputStream is = new DataInputStream(new BufferedInputStream(client.getInputStream()));
//4.读入 数据
String msg = is.readUTF();
//处理数据
String name = "";
String pwd = "";
String[] arr = msg.split("&");
for(String str : arr){
String[] a = str.split("=");
if("username".equals(a[0])){
name = a[1];
}else if("password".equals(a[0])){
pwd = a[1];
}
}
//获取输出流 响应给客户端结果
DataOutputStream os = new DataOutputStream(new BufferedOutputStream(client.getOutputStream()));
//判断
if("laopei".equals(name) && "1234".equals(pwd)){
os.writeUTF("登录成功");
}else{
os.writeUTF("登录失败");
}
//刷出
os.flush();
//5.关闭
os.close();
is.close();
client.close();
server.close();
}
}
基恩士成长空间 419人发布