网络编程
1.1网络通信的要素
如何实现网络通信?
通信双方的地址:
- ip
- 端口号
规则:网络通信的协议
TCP/IP参考模型:
小结:
-
网络编程中两个主要的问题
- 如何准确的定位到网络上的一台主机或者多台主机
- 如何进行通信
-
网络编程要素
- Ip和端口号 IP
- 网络通信协议 UDP TCP
-
万物皆对象
1.2 IP
ip地址:InetAddress
-
唯一定位一台网络计算机
-
127.0.0.1:本地localhost
-
ip地址的分类
- ipv4、ipv6
- 公网-私网
-
域名:记忆IP问题!
-
IP
public static void main(String[] args) throws UnknownHostException { //查询本机地址 InetAddress inetAddress = InetAddress.getByName("127.0.0.1"); System.out.println(inetAddress); InetAddress localhost = InetAddress.getByName("localhost"); System.out.println(localhost); System.out.println(InetAddress.getLocalHost()); //查询网站ip地址 InetAddress inetAddress1 = InetAddress.getByName("www.baidu.com"); System.out.println(inetAddress1); //常用方法 System.out.println(inetAddress1.getAddress()); System.out.println(inetAddress1.getCanonicalHostName()); //规范的名字 System.out.println(inetAddress1.getHostAddress()); //ip System.out.println(inetAddress1.getHostName()); //域名,或者是自己电脑的名字 }
-
1.3 端口
端口表示计算机上的一个程序的进程
-
不同的进程有不同的端口号!用来区分软件
-
被规定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 #打开任务管理
public static void main(String[] args) { InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1",8080); InetSocketAddress socketAddress1 = new InetSocketAddress("localhost", 8080); System.out.println(socketAddress); System.out.println(socketAddress1); System.out.println(socketAddress.getAddress()); System.out.println(socketAddress.getHostName()); //host System.out.println(socketAddress.getPort()); //端口 }
-
1.4 通信协议
协议:约定.
网络通信协议:速率,传输码率,代码结构,传输控制.....
问题:非常复杂
大事化小:分层!
TCP/IP协议簇
重要:
- TCP :用户传输协议
- UDP:用户数据报协议
出名的协议:
- TCP:
- Ip:网络互联协议
TCP 和 UDP对比
1.5 TCP
客户端
-
链接服务器Socket
-
发送消息
public static void main(String[] args) { OutputStream outputStream=null; Socket socket =null; try { //1.知道服务器地址,端口号 InetAddress serverIp = InetAddress.getByName("127.0.0.1"); int port = 9999; //2.创建一个socket链接 socket = new Socket(serverIp, port); //发送消息 IO流 outputStream = socket.getOutputStream(); outputStream.write("你好,欢迎学习Java".getBytes()); } catch (Exception e) { e.printStackTrace(); }finally { if (outputStream!=null){ try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket!=null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
服务器
- 建立服务器端口ServerSocket
- 等待用户的链接 accept
- 接收用户消息
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket =null;
InputStream inputStream =null;
ByteArrayOutputStream byteArrayOutputStream =null;
try {
//1.我有一个地址
serverSocket = new ServerSocket(9999);
while(true){ //用于一直结束客户端消息
//2. 等待客户端链接
socket = serverSocket.accept();
//3.读取客户端的消息
inputStream = socket.getInputStream();
//管道流
byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len=inputStream.read(buffer))!=-1){
byteArrayOutputStream.write(buffer,0,len);
}
System.out.println(byteArrayOutputStream.toString());
}
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭资源
if (byteArrayOutputStream!=null){
try {
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
文件上传
- 客户端
public static void main(String[] args) throws Exception {
//1.创建一个socket链接
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
//2.创建一个输出流
OutputStream outputStream = socket.getOutputStream();
//3.读取文件
FileInputStream fis = new FileInputStream(new File("15.jpg"));
//4.写出文件
byte[] buffer = new byte[1024];
int len;
while ((len=fis.read(buffer))!=-1){
outputStream.write(buffer,0,len);
}
//通知服务器,已经传输完成
socket.shutdownOutput();
//确定服务器接收完毕,才能断开链接
InputStream inputStream = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer2 = new byte[1024];
int len2;
while ((len2=inputStream.read(buffer2))!=-1) {
baos.write(buffer2,0,len2);
}
System.out.println(baos.toString());
//5.关闭资源
baos.close();
inputStream.close();
fis.close();
outputStream.close();
socket.close();
}
- 服务器端
public static void main(String[] args) throws Exception {
//1.创建服务
ServerSocket serverSocket = new ServerSocket(9000);
//2.监听客户端链接
Socket socket = serverSocket.accept();//阻塞式监听,一直当地啊客户端链接
//3.获取输入流
InputStream is = socket.getInputStream();
//4.文件输出
FileOutputStream fos = new FileOutputStream(new File("a.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());
//关闭资源
fos.close();
is.close();
socket.close();
serverSocket.close();
}
Tomcat
服务端
- 自定义
- Tomcat服务器
客户端
- 自定义 C
- 浏览器 B
1.6 UDP
发短息:不用链接,需要知道对方的地址!
发送消息
public static void main(String[] args) throws Exception {
//1.建立一个socket
DatagramSocket socket = new DatagramSocket();
//2.建个包
String msg = "你好呀,服务器";
//发送给谁
InetAddress localhost = InetAddress.getByName("localhost");
int port =9090;
//数据,数据长度起始,要发送给谁
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
//3.发送包
socket.send(packet);
//关闭流
socket.close();
}
接收消息
public static void main(String[] args) throws Exception {
//开放端口
DatagramSocket socket = new DatagramSocket(9090);
//接收数据
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();
}
循环发送消息
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(8888);
//准备数据:控制台读取 System.in
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true){
String data = reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",6666));
socket.send(packet);
if (data.equals("bye")){
break;
}
}
socket.close();
}
循环接收消息
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(6666);
//准备接收包裹
while (true){
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container,0,container.length);
socket.receive(packet);//阻塞式接收包裹
//断开链接 bye
byte[] data = packet.getData();
String receiveData = new String(data, 0, data.length);
if (receiveData.equals("bye")){
break;
}
System.out.println(receiveData);
}
socket.close();
}
聊天
- 发送方
package com.yuwei.chat;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class TalkSend implements Runnable{
private DatagramSocket socket = null;
private BufferedReader reader = null;
private String toIp;
private int toPort;
public TalkSend(int fromPort, String toIp, int toPort) {
this.toIp = toIp;
this.toPort = toPort;
try {
socket = new DatagramSocket(fromPort);
reader=new BufferedReader(new InputStreamReader(System.in));
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void run() {
while (true){
try {
String data = reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new
DatagramPacket(datas,0,datas.length,
new InetSocketAddress(this.toIp,this.toPort));
//4. 发送包裹send
socket.send(packet);
//退出判断
if (data.equals("bye")){
break;
}
}catch (Exception e){
e.printStackTrace();
}
}
//5. 释放资源
socket.close();
}
}
- 接收方
package com.yuwei.chat;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
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(port);
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void run() {
while (true){
try{
byte[] container =new byte[1024];
DatagramPacket packet = new DatagramPacket(container, 0, container.length);
socket.receive(packet);//阻塞式接收
byte[] data = packet.getData();
String receiveData = new String(data, 0, data.length);
System.out.println(msgFrom + ": " + receiveData);
//断开链接 bye
if (receiveData.equals("bye")){
break;
}
}catch (Exception e){
e.printStackTrace();
}
}
socket.close();
}
}
- 学生线程
package com.yuwei.chat;
public class TalkStudent {
public static void main(String[] args) {
//开启两个线程
new Thread(new TalkSend(7777,"localhost",9999)).start();
new Thread(new TalkReceive(8888,"老师")).start();
}
}
- 教师线程
package com.yuwei.chat;
public class TalkTeacher {
public static void main(String[] args) {
new Thread(new TalkReceive(9999,"学生")).start();
new Thread(new TalkSend(5555,"localhost",8888)).start();
}
}
1.7 URL
统一资源定位符:定位资源的,定位互联网上的某一个资源
协议:// ip地址:端口号/项目名/资源
package com.kuang.lesson6;
import java.net.MalformedURLException;
import java.net.URL;
public class URLDemo01 {
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:8080/helloworld/index.jsp?
username=kuangshen&password=123");
System.out.println(url.getProtocol()); //获取URL的协议名
System.out.println(url.getHost()); //获取URL的主机名
System.out.println(url.getPort()); //获取URL的端口号
System.out.println(url.getPath()); //获取URL的文件路径
System.out.println(url.getFile()); //获取URL的文件名
System.out.println(url.getQuery()); //获取URL的查询名
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
下载tomcat下的文件
首先需要在tomcat中放入一个资源文件!
package com.kuang.lesson6;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class URLDemo02 {
public static void main(String[] args) {
try {
//1. 定位到服务器端的资源
URL url = new URL("http://localhost:8080/helloworld/qinjiang.jpg");
//2. 链接这个资源 HTTP
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//3. 获取输入流
InputStream is = connection.getInputStream();
//4. 写出文件
FileOutputStream fos = new FileOutputStream("qinjiang2.jpg");
byte[] buffer = new byte[1024];
int len;
while ((len=is.read(buffer))!=-1){
fos.write(buffer,0,len); //写出这个数据
}
//关闭资源
fos.close();
is.close();
connection.disconnect(); //断开连接
} catch (Exception e) {
e.printStackTrace();
}
}
}