网络编程
概述
javaweb:网页编程 B/S
网络编程:TCP/IP C/S
网络通讯的要素
如何实现网络的通信?
通信双方地址:
- ip
- 端口号
- 192.168.16,124:5900
-
网络编程中有两个主要的问题
-
如何准确定位到网络上一台或者多台主机
-
找到主机之后如何进行通信
-
-
网络编程中的要素
- ip号和端口号
- 网络通信协议
-
万物皆对象
IP地址
import java.net.InetAddress;
import java.net.UnknownHostException;
public class TestAdress {
public static void main(String[] args) throws UnknownHostException {
//获取百度的地址
InetAddress inetAddress2=InetAddress.getByName("www.baidu.com");
System.out.println(inetAddress2);
//获取主机地址
InetAddress inetAddress1=InetAddress.getByName("127.0.0.1");
System.out.println(inetAddress1);
InetAddress inetAddress3=InetAddress.getByName("localhost");
System.out.println(inetAddress3);
InetAddress inetAddress4=InetAddress.getLocalHost();
System.out.println(inetAddress4);
//常用方法
System.out.println(inetAddress2.getAddress());
System.out.println(inetAddress2.getCanonicalHostName());//规范的名字
System.out.println(inetAddress2.getHostAddress());//ip
System.out.println(inetAddress2.getHostName());//域名,或者自己电脑的名称
}
}
/*
www.baidu.com/180.101.49.11
/127.0.0.1
localhost/127.0.0.1
DESKTOP-7HL5RO6/192.168.188.1
[B@1b6d3586
180.101.49.12
180.101.49.12
www.baidu.com
*/
端口
端口表示计算机上的一个程序的进程
-
不同的进程有不同的端口号,用来区分软件
-
被规定0~65535
- TCP,UDP:65535*2 tcp:80,udp:80,单个协议下,端口号不能冲突
-
端口分类
- 公有端口0~1023
- HTTP:80
- HTTPS:443
- FTP:21
- Telent:23
- 程序注册端口:1024~49151,分配用户或者程序
- Tomcat:8080
- MySql:3306
- Oracle:1521
- 动态、私有:49152~65535
netstat -ano #查看所有的端口 netstat -ano|findstr "5900" #查看指定的端口 tasklist|findstr "8696" #查看指定端口的进程 Ctrl+shift+ESC
import java.net.InetSocketAddress; public class TestSocketAdress { public static void main(String[] args) { InetSocketAddress socketAddress1=new InetSocketAddress("127.0.0.1",8080); InetSocketAddress socketAddress2=new InetSocketAddress("localhost",8080); System.out.println(socketAddress1); System.out.println(socketAddress2); System.out.println(socketAddress1.getAddress()); System.out.println(socketAddress1.getHostName());//地址 System.out.println(socketAddress1.getPort());//端口 } } /* /127.0.0.1:8080 localhost/127.0.0.1:8080 /127.0.0.1 activate.navicat.com 8080 */
- 公有端口0~1023
通信协议
TCP UDP 对比
TCP:打电话
- 连接,稳定
- 三次握手,四次挥手
- 客户端,服务端
- 传输完成,释放连接,效率低
UDP:发短信
- 不连接,不稳定
- 客户端,服务端:没有明确的界限
- 不管有没有准备好,都可以发给你
TCP
客户端
- 连接服务器
- 发送消息
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class TcpClient01 {
public static void main(String[] args) {
InetAddress inetAddress=null;
Socket socket=null;
OutputStream outputStream=null;
try {
//获得服务器地址、端口号
inetAddress=InetAddress.getByName("127.0.0.1");
int port=9999;
//创建连接
socket=new Socket(inetAddress,port);
outputStream= socket.getOutputStream();
outputStream.write("hello".getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally{
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(outputStream!=null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
服务器
- 建立服务的端口 SeverSocket
- 等待用户的连接 accept
- 接收用户的消息
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpSever01 {
public static void main(String[] args) {
ServerSocket serverSocket=null;
Socket socket=null;
InputStream inputStream=null;
ByteArrayOutputStream baos=null;
try {
//服务器地址
serverSocket=new ServerSocket(9999);
while(true){
//等待连接
socket=serverSocket.accept();
//读取客户端消息
inputStream=socket.getInputStream();
//管道流
baos=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len;
while((len=inputStream.read(buffer))!=-1){
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
}
/*
byte[] buffer=new byte[1024];
int len;
while((len=inputStream.read(buffer))!=-1){
String msg=new String(buffer,0,len);
System.out.println(msg);
}
*/
} catch (IOException e) {
e.printStackTrace();
}finally{
if(baos!=null){
try{
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
文件上传
服务器
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpSever02 {
public static void main(String[] args) throws IOException {
//服务器地址
ServerSocket serverSocket=new ServerSocket(9999);
//等待客户端连接
Socket socket=serverSocket.accept();
//获取输入流
InputStream is=socket.getInputStream();
//输出文件
FileOutputStream fos=new FileOutputStream("copy4.jpg");
byte[] buffer=new byte[1024];
int len;
while((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
//通知客户端,已经接收完毕
OutputStream os=socket.getOutputStream();
os.write("接收完毕,可以断开连接".getBytes());
//关闭资源
serverSocket.close();
socket.close();
is.close();
fos.close();
os.close();
}
}
客户端
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TcpClient02 {
public static void main(String[] args) throws IOException {
//获取服务器地址,端口号
InetAddress SeverAdress=InetAddress.getByName("127.0.0.1");
int port=9999;
//创建连接
Socket socket=new Socket(SeverAdress,9999);
//创建一个输出流
OutputStream os=socket.getOutputStream();
//读取文件
FileInputStream fis=new FileInputStream("F://Typora文本//4.jpg");
//写出文件
byte[] buffer1=new byte[1024];
int len1;
while((len1=fis.read(buffer1))!=-1){
os.write(buffer1,0,len1);
}
//通知服务器,已经接收完毕
socket.shutdownOutput();
//确认服务器传输完毕,才断开连接
InputStream is=socket.getInputStream();
//String bytes[]
ByteArrayOutputStream baos=new ByteArrayOutputStream();
byte[] buffer2=new byte[2048];
int len2;
while((len2=is.read(buffer2))!=-1){
baos.write(buffer2,0,len2);
}
System.out.println(baos.toString());
//关闭资源
socket.close();
os.close();
fis.close();
is.close();
baos.close();
}
}
Tomcat
服务端
- 自定义 S
- Tomcat服务器 S:Java后台开发
客户端
- 自定义 C
- 浏览器 B
UDP
服务端
import java.net.DatagramPacket;
import java.net.DatagramSocket;
//等待客户端连接
public class UdpSever01 {
public static void main(String[] args) throws Exception {
//开放端口
DatagramSocket socket=new DatagramSocket(9998);
//接收包
byte[] buffer=new byte[1024];
DatagramPacket packet=new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet);//阻塞接收
System.out.println(packet.getAddress().getHostAddress());
System.out.println(new String(packet.getData(),0,packet.getLength()));
//关闭流
socket.close();
}
}
客户端
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpClient01 {
public static void main(String[] args) throws Exception {
//不需要连接,但需要知道服务器地址
InetAddress severadress=InetAddress.getByName("127.0.0.1");
int port=9998;
//建立一个socket
DatagramSocket socket=new DatagramSocket();
//创建包
String msg="你好,服务器";
//数据,数据的开始位置,数据的长度,要发送给谁
DatagramPacket packet=new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,severadress,port);
//发送包
socket.send(packet);
//关闭流
socket.close();
}
}
咨询(单方发送消息)
发送端
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class UdpSend01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket=new DatagramSocket();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
while(true){
String breader=bufferedReader.readLine();
byte[] data=breader.getBytes();
DatagramPacket packet=new DatagramPacket(data,0,data.length,new InetSocketAddress("localhost",9997));
socket.send(packet);
if(breader.equals("bye")){
break;
}
}
socket.close();
}
}
接收端
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpReceive01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket=new DatagramSocket(9997);
while(true){
//接收包裹
byte[] rdata=new byte[1024];
DatagramPacket packet=new DatagramPacket(rdata,0,rdata.length);
socket.receive(packet);//阻塞式接收
//断开连接
byte[] data= packet.getData();
String datas=new String(data,0, packet.getLength());//使用packet.getData().getLength()输出结果会出现乱码
System.out.println(datas);
if(datas.equals("bye")){
break;
}
}
socket.close();
}
}
在线咨询
发送端
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
public class TalkSend implements Runnable{
DatagramSocket socket=null;
BufferedReader bufferedReader=null;
private int fromPort;
private String toIP;
private int toPort;
public TalkSend(int fromPort,String toIP,int toPort){
this.fromPort=fromPort;
this.toIP=toIP;
this.toPort=toPort;
try {
socket=new DatagramSocket(fromPort);
bufferedReader=new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while(true){
try{
String breader=bufferedReader.readLine();
byte[] data=breader.getBytes();
DatagramPacket packet=new DatagramPacket(data,0,data.length,new InetSocketAddress(this.toIP,this.toPort));
socket.send(packet);
if(breader.equals("bye")){
break;
}
}catch (Exception e){
e.printStackTrace();
}
}
socket.close();
}
}
接收端
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class TalkReceive implements Runnable{
DatagramSocket socket=null;
private int port;
private String msgfrom;
public TalkReceive(int port,String msgfrom){
this.port=port;
this.msgfrom=msgfrom;
try {
socket=new DatagramSocket(this.port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while(true){
try{
//接收包裹
byte[] rdata=new byte[1024];
DatagramPacket packet=new DatagramPacket(rdata,0,rdata.length);
socket.receive(packet);//阻塞式接收
//断开连接
byte[] data= packet.getData();
String datas=new String(data,0, packet.getLength());
System.out.println(msgfrom+":"+datas);
if(datas.equals("bye")){
break;
}
}catch (Exception e){
e.printStackTrace();
}
}
socket.close();
}
}
学生
public class Thread01 {
public static void main(String[] args) {
//两个线程
new Thread(new TalkSend(9996,"localhost",9995)).start();
//接收端口要与发送端口一致
new Thread(new TalkReceive(9994,"老师")).start();
}
}
老师
public class Thread02 {
public static void main(String[] args) {
new Thread(new TalkSend(9993,"localhost",9994)).start();
new Thread(new TalkReceive(9995,"学生")).start();
}
}
URL
https://www.baidu.com/
统一资源定界符:定位资源的,地位互联网上的某一个资源
DNS域名解析:www.baidu.com xxx.x…x…x
协议://ip地址:端口/项目名/资源
获取信息
import java.net.MalformedURLException;
import java.net.URL;
public class Urltext {
public static void main(String[] args) throws MalformedURLException {
URL url= new URL("https://localhost:8080/helloworld/index.jsp?username=hello&password=123");
System.out.println(url.getProtocol());//协议
System.out.println(url.getPath());//全路径
System.out.println(url.getPort());//端口
System.out.println(url.getFile());//文件
System.out.println(url.getQuery());//参数
System.out.println(url.getHost());//主机ip
}
}
/*
https
/helloworld/index.jsp
8080
/helloworld/index.jsp?username=hello&password=123
username=hello&password=123
localhost
*/
下载资源
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class urlDown {
public static void main(String[] args) throws Exception {
//下载地址 需要打开Tomcat
URL url=new URL("http://localhost:8080/usertext/practice.txt");
//连接到这个资源 使用HTTP
HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
//获取输入流
InputStream is=urlConnection.getInputStream();
//输出到文件
FileOutputStream fos=new FileOutputStream("practice.txt");
byte[] buffer=new byte[1024];
int len;
while((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
fos.close();
is.close();
urlConnection.disconnect();//断开连接
}
}
右击网页,点击审查元素,选择网络,可从中获取url。