网络编程
一.前言
定位一台计算机或者网站,一般通过ip地址+端口号。
比如在dos窗口输入命令ping www.baidu.com
,就可以与其通信。
可以通过命令ipconfig
查看本机的ip配置信息。
-
在域名的旁边显示的14.215.177.39就是百度的ip地址。
-
网络编程需要的基本要素:ip地址、端口号、网络通信协议。
-
ip地址能够唯一定义网络上一台计算机,有一些比较特殊的ip地址,如本机的ip地址127.0.0.1,也就是localhost。
-
ip地址分为ipv4和ipv6。
-
ipv4由四个字节组成,具体分为ABCDE五类。
A:1.0.0.0~127.255.255.255
B:128.0.0.0~191.255.255.255
C:192.0.0.0~223.255.255.255
D:224.0.0.0~239.255.255.255 -
端口:0~65535,其中0到1023是公有端口,尽量不要使用;一些特殊的端口,如数据库默认端口3306,Tomcat默认端口8080,TCP端口80,UDP端口:80,HTTP端口80,HTTPS端口443,FTP端口21,Telent端口23等,一般程序注册端口为1024到49151。通过命令
netstat -ano
可以查看本机的端口使用情况。 -
-
TCP和UDP是两种不同的通信协议,它们都有0~65535个端口。
-
TCP建立连接:三次握手
A:你瞅啥?
B:瞅你咋地!
A:干一架?
- TCP断开连接:四次挥手
A:我们分手吧,我要走了
B:你要走吗?
B:你真的要走吗?
A:是的,我们的故事结束了。
二.InetAdress类
public static void main(String[] args) {
try {
InetAddress inetAddress1=InetAddress.getByName("www.baidu.com");
InetAddress inetAddress2=InetAddress.getByName("localhost");
InetAddress inetAddress3=InetAddress.getLocalHost();
System.out.println(inetAddress1);
System.out.println(inetAddress2);
System.out.println(inetAddress3);
//常用方法
System.out.println(inetAddress1.getAddress());
System.out.println(inetAddress1.getCanonicalHostName());
System.out.println(inetAddress1.getHostAddress());
System.out.println(inetAddress1.getHostName());
} catch (UnknownHostException ex) {
ex.printStackTrace();
}
}
运行信息
三.TCP实现通信
1、建立TCP客户端程序
package com.han.TCP;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClient {
public static void main(String[] args) throws IOException {
// 服务器的地址和端口
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
// 创建socket连接
Socket socket = new Socket(serverIP, port);
// 发送消息
OutputStream os = socket.getOutputStream();
os.write("服务器你好,我是客户端".getBytes());
if (os != null) {
os.close();
}
if (socket != null) {
socket.close();
}
}
}
2、建立TCP服务端程序
package com.han.TCP;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
public static void main(String[] args) throws IOException {
// 服务器端口
ServerSocket serverSocket=new ServerSocket(9999);
// 等待客户端连接过来
Socket socket=serverSocket.accept();
// 读取客户端发送的消息
InputStream is=socket.getInputStream();
// 管道流
ByteArrayOutputStream baos=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len;
while((len=is.read(buffer))!=-1){
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
if(baos!=null){
baos.close();
}
if(is!=null){
baos.close();
}
if(socket!=null){
is.close();
}
if(serverSocket!=null){
serverSocket.close();
}
is.close();
socket.close();
serverSocket.close();
}
}
先运行服务端程序,再运行客户端程序。可以在服务端看到客户端发过来的消息。
四.TCP文件上传
1、编写服务器程序
package com.han.TCP;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServerFile {
public static void main(String[] args) throws IOException {
// 创建服务
ServerSocket serverSocket=new ServerSocket(9000);
// 监听客户端的连接:阻塞监听,一直等待
Socket socket=serverSocket.accept();
// 获取输入流
InputStream is=socket.getInputStream();
// 文件输出
FileOutputStream fos=new FileOutputStream(new File("recevie.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();
}
}
}
2、编写客户端程序
准备要上传的文件,这里是yali.jpg
package com.han.TCP;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class TCPClientFile {
public static void main(String[] args) throws IOException {
// 创建socket连接
Socket socket=new Socket(InetAddress.getByName("127.0.0.1"),9000);
// 创建输出流
OutputStream os=socket.getOutputStream();
// 读取文件
FileInputStream fis=new FileInputStream(new File("yali.jpg"));
// 写出文件
byte[] buffer=new byte[1024];
int len;
while ((len=fis.read(buffer))!=-1){
os.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());
// 关闭资源
baos.close();
inputStream.close();
os.close();
fis.close();
os.close();
socket.close();
}
}
先运行服务器程序,再运行客户端程序。运行结果显示已经将文件上传。
五.UDP通信
发送方发送消息,接收方接收消息
1、编写发送方程序
package com.han.UDP;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
public class UDPSender {
public static void main(String[] args) throws IOException {
DatagramSocket socket=new DatagramSocket(8888);
// 准备数据
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();
}
}
2、编写接收方程序
package com.han.UDP;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UDPReceive {
public static void main(String[] args) throws IOException {
DatagramSocket socket=new DatagramSocket(6666);
while (true){
// 准备接收包裹
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(receiveData);
if(receiveData.equals("bye")){
break;
}
}
socket.close();
}
}
先运行发送方程序,再运行接收方程序,运行测试。
现在只能发送方发送信息,接收方接收消息。我们想让两者能够互相发送,那么就要开启线程。
开启线程,两者互相发送消息
1、编写talksender程序
package com.han.thread;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class talkSend implements Runnable {
DatagramSocket socket=null;
BufferedReader reader=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);
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));
socket.send(packet);
if(data.equals("bye")){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
2、编写talkReceive程序
package com.han.thread;
import java.io.IOException;
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 msgForm;
public talkReceive(int port,String msgForm) {
this.port = port;
this.msgForm=msgForm;
try {
socket=new DatagramSocket(port);
} catch (SocketException 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(msgForm+":"+receiveData);
if (receiveData.equals("bye")) {
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
编写talkone程序,开启两个线程
package com.han.thread;
public class talkOne {
public static void main(String[] args) {
// 开启两个线程
new Thread(new talkSend(7777,"localhost",9999)).start();
new Thread(new talkReceive(8888,"talktwo")).start();
}
}
编写talktwo程序,开启两个线程
package com.han.thread;
public class talktwo {
public static void main(String[] args) {
// 开启两个线程
new Thread(new talkSend(5555,"localhost",8888)).start();
new Thread(new talkReceive(9999,"talkone")).start();
}
}
依次运行talkone和talktwo,即可互相发送信息,运行验证。
六.URL下载网络资源
编写URLTest程序
package com.han.URL;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class URLTest {
public static void main(String[] args) throws Exception {
URL url= new URL("https://m801.music.126.net/20200824173512/ee0abf07d9c684df81c20aea96d03ded/jdyyaac/025f/005a/560b/550fc4000370bf8ea74baa716547b3d5.m4a");
HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
InputStream inputStream=urlConnection.getInputStream();
FileOutputStream fos=new FileOutputStream("z.m4a");
byte[] buffer=new byte[1024];
int len;
while ((len=inputStream.read(buffer))!=-1){
fos.write(buffer,0,len);
}
fos.close();
inputStream.close();
urlConnection.disconnect();
}
}
URL("https://music.163.com/#/song?id=531295576");
是定位到网上的一个资源,可自行更改。"z.m4a"
是下载后生成的文件名,也可自行更改,不过类型要对应,否则无法下载。
运行程序,验证,生成z.m4a文件。
拖到桌面,播放它。
最美的期待