文章目录
07 网络编程
7-1 网络编程概述
Java是Internet上的语言,它从语言级别上提供了对网络应用程序的支持。
Java提供的网络类库,可以实现无痛的网络连接,联网的底层细节被隐藏在Java本机安装系统里,由JVM进行控制。
另外,Java实现了一个跨平台的网络库,程序员面对的是一个统一的网络编程环境。
7-2 网络通信要素
通信要素1: IP和端口号
IP和InetAddress类
Java中使用InetAddress类代表IP地址。
本地回路地址:127.0.0.1
两个常用方法:
- getHostName()
- getHostAddress()
端口号
端口号标识正在计算机上运行的进程(程序),它被规定为一个16位的整数(0~65535),不同的进程有不同的端口号。
端口可分为公认端口、注册端口、动态/私有端口:
- 公认端口:0~1023,由预先定义的服务通信占用(HTTP=80, FTP=21, Telnet=23)
- 注册端口:1024~49151,分配给用户进程或应用程序(Tomcat=8080, MySQL=3306, Oracle=1521)
- 动态/私有端口:49152~65535
端口号与IP地址的组合得出一个网络套接字:Socket
通信要素2: 网络协议
网络通信协议对计算机网络通信中的速率、传输代码、代码结构、传输控制步骤、出错控制等方面制定了相关标准。
通信协议的分层思想:在制定协议时,把复杂成分分解为一些简单的成分,再将它们复合起来。最常用的复合方式是层次方式,
即同层间可以通信、上一层可以调用下一层,而与再下一层不发生关系;各层互不影响,利于系统的开发和扩展。
TCP/IP以其两个主要协议——传输控制协议(TCP)和网络互联协议(IP)而得名,实际上是一组协议,包括多个具有不同功能且互为关联的协议。
在传输层协议中有两个非常重要的协议:
- 传输控制协议TCP(Transmission Control Protocol)
- 用户数据包协议UDP(User Datagram Protocol)
TCP
- 使用TCP协议前,须先建立TCP连接,形成传输数据通道
- 传输前,采用“三次握手”方式,点对点通信,是可靠的
- TCP协议进行通信的两个应用进程:客户端、服务端
- 在连接中可进行大数据量的传输
- 传输完毕,需释放已建立的连接,效率低
UDP
- 将数据、源、目的封装成数据包,不需要建立连接
- 每个数据包的大小限制在64K内
- 发送不管对方是否准备好,接收方收到也不确认,不可靠
- 可以广播发送
- 发送数据结束时无需释放资源,开销小,速度快
7-3 网络编程
TCP网络编程
例1:客户端发送信息给服务端,服务端将数据显示在控制台
public class TCPTest1 {
@Test
public void client() {
Socket socket = null;
OutputStream os = null;
try {
//1. 创建Socket对象,指明服务器端的IP和端口号
InetAddress inet = InetAddress.getByName("127.0.0.1");
socket = new Socket(inet, 65535);
//2. 获取一个输出流,用于写数据
os = socket.getOutputStream();
os.write("Hello, this is the client.".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
//3. 关闭资源
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void server() {
ServerSocket ss = null;
Socket accept = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
//1. 创建服务器端的ServerSocket,指明自己的端口号
ss = new ServerSocket(65535);
//2. 调用accept()表示接受来自于客户端的socket
accept = ss.accept();
//3. 获取输入流
is = accept.getInputStream();
//4. 读取流数据并从控制台输出
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[5];
int len;
while((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
System.out.println(baos.toString());
System.out.println("由" + accept.getInetAddress().getHostAddress() + "发送");
} catch (IOException e) {
e.printStackTrace();
} finally {
//5. 关闭资源
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (accept != null) {
try {
accept.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
例2:客户端发送文件给服务端,服务端将文件保存在本地
public class TCPTest2 {
@Test
public void client() {
Socket socket = null;
OutputStream ops = null;
FileInputStream fis = null;
try {
socket = new Socket(InetAddress.getByName("localhost"), 65535);
ops = socket.getOutputStream();
fis = new FileInputStream(new File("SatomiMyWife.jpg"));
byte[] buffer = new byte[256];
int len;
while ((len = fis.read(buffer)) != -1) {
ops.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (ops != null) {
try {
ops.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void server() {
ServerSocket ss = null;
Socket socket = null;
InputStream is = null;
FileOutputStream fos = null;
try {
ss = new ServerSocket(65535);
socket = ss.accept();
is = socket.getInputStream();
File file = new File("SatomiCopy.jpg");
fos = new FileOutputStream(file);
byte[] buffer = new byte[256];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
System.out.println("收到了来自" + socket.getInetAddress().getHostName() + "的文件(" + file.length() + "bytes)");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
例3:从客户端发送文件给服务端,服务端保存到本地,并返回“发送成功”给客户端
public class TCPTest3 {
@Test
public void client() {
Socket socket = null;
OutputStream ops = null;
FileInputStream fis = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
socket = new Socket(InetAddress.getByName("127.0.0.1"), 65535);
ops = socket.getOutputStream();
fis = new FileInputStream(new File("SatomiMyWife.jpg"));
byte[] buffer = new byte[256];
int len;
while ((len = fis.read(buffer)) != -1) {
ops.write(buffer, 0, len);
}
//图片发完,已不再去输出数据了;需要关闭输出流,等待接收客户端数据
socket.shutdownOutput();
//接收反馈
is = socket.getInputStream();
baos = new ByteArrayOutputStream();
byte[] feedback = new byte[20];
int fb;
while ((fb = is.read(feedback)) != -1) {
baos.write(feedback, 0, fb);
}
System.out.println(baos.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (ops != null) {
try {
ops.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void server() {
ServerSocket ss = null;
Socket socket = null;
InputStream is = null;
FileOutputStream fos = null;
OutputStream os = null;
try {
ss = new ServerSocket(65535);
socket = ss.accept();
is = socket.getInputStream();
fos = new FileOutputStream(new File("SatomiChan.jpg"));
byte[] buffer = new byte[256];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
System.out.println("成功接收文件");
//接收成功发送反馈
os = socket.getOutputStream();
os.write(("Accepted data successfully").getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
UDP网络编程
基本示例:
public class UDPTest {
//发送端
@Test
public void send() throws IOException {
DatagramSocket socket = new DatagramSocket();
String str = "Hello from UDP";
byte[] data = str.getBytes();
InetAddress inet = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(data, 0, data.length, inet, 9090);
socket.send(packet);
socket.close();
}
//接收端
@Test
public void receiver() throws IOException {
DatagramSocket socket = new DatagramSocket(9090);
byte[] buffer = new byte[100];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);
System.out.println(new String(packet.getData(), 0, packet.getLength()));
socket.close();
}
}
URL网络编程
URL(Uniform Resource Locator): 统一资源定位符,它表示Internet上某一资源的地址。
通过URL我们可以访问Internet上的各种网络资源,比如最常见的www, ftp站点。
URL的基本结构由5部分构成:
<传输协议>://<主机名>:<端口号>/<文件名>#片段名?参数列表