JAVA——网络编程
InetAddress类
实例化
public static void main(String[] args){
InetAddress inet1 = null;
InetAddress inet2 = null;
try {
inet1 = InetAddress.getByName("192.168.10.14");//IP
System.out.println(inet1);///192.168.10.14
inet2 = InetAddress.getByName("www.baidu.com");//域名
System.out.println(inet2);//www.baidu.com/36.152.44.95
//获取本机ip
InetAddress inet3 = InetAddress.getByName("127.0.0.1");
InetAddress inet4 = InetAddress.getLocalHost();
System.out.println(inet3);//127.0.0.1
System.out.println(inet4);//LAPTOP-xxxx/192.168.196.1
//常用方法:
//getHostName()
System.out.println(inet2.getHostName());
//www.baidu.com
//getHostAddress()
System.out.println(inet2.getHostAddress());
//36.152.44.96
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
Socket套接字
- IP区分主机
- 端口号区分进程:l6位整数:0~65535
TCP与UDP
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QP2NntJS-1636462700317)(C:\Users\10153\AppData\Roaming\Typora\typora-user-images\image-20211109150728496.png)]
TCP网络通信
例子1:客户端发送信息给服务端,服务端将数据显示在控制台上
-
步骤:
-
客户端
-
创建Socket对象,指明服务器端的ip和端口号
-
获取一个输出流,用于输出数据
-
写出数据的操作
-
资源的关闭
-
-
服务器端
- 创建服务器端的ServerSocket,指明自己的端口号
- 调用accept()表示接收到的socket
- 获取输入流
- 读取接收的数据
- 资源的关闭
-
-
实现(先运行服务器端的代码):
import org.junit.Test; import java.io.*; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class TCPTest1 { @Test //客户端 public void client() { Socket socket = null; OutputStream os = null; try { //1. 创建Socket对象,指明服务器端的ip和端口号 InetAddress inet = InetAddress.getLocalHost(); socket = new Socket(inet.getHostAddress(),8888); //2. 获取一个输出流,用于输出数据 os = socket.getOutputStream(); //3. 写出数据的操作 os.write("你好,我是客户端".getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { // 4. 资源的关闭 try { if (os != null) os.close(); } catch (IOException e) { e.printStackTrace(); } try { if (socket != null) socket.close(); } catch (IOException e) { e.printStackTrace(); } } } @Test //服务端 public void server(){ ServerSocket serverSocket = null; Socket socket = null; InputStream is = null; ByteArrayOutputStream baos = null; try { //1. 创建服务器端的ServerSocket,指明自己的端口号 serverSocket = new ServerSocket(8888); //2. 调用accept()表示接收到的socket socket = serverSocket.accept(); //3. 获取输入流 is = socket.getInputStream(); //可能会有乱码,不建议这么操作 // byte[] buffer = new byte[5]; // int len; // while ((len = is.read(buffer)) != -1){ // String s = new String(buffer, 0, len); // System.out.println(s); // }// // 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("收到了来自于:"+socket.getInetAddress().getHostAddress()+"的数据"); } catch (IOException e) { e.printStackTrace(); } finally { //5. 资源的关闭 try { if(is != null) is.close(); } catch (IOException e) { e.printStackTrace(); } try { if (socket != null) socket.close(); } catch (IOException e) { e.printStackTrace(); } try { if (baos != null) baos.close(); } catch (IOException e) { e.printStackTrace(); } try { if (serverSocket != null) serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
例子2:客户端发送文件给服务端,服务端将文件保存在本地
import org.junit.Test;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPTest2 {
@Test
public void client(){
Socket socket = null;
Socket socket1 = null;
OutputStream os = null;
OutputStream osFileName = null;
BufferedInputStream bis = null;
try {
socket = new Socket(InetAddress.getLocalHost().getHostAddress(),9999);
socket1 = new Socket(InetAddress.getLocalHost().getHostAddress(),9999);
osFileName = socket.getOutputStream();//存放文件名字
os = socket1.getOutputStream();//存放文件
File file = new File("client(服务器接收)(服务器接收).txt");//此处填写文件名
FileInputStream fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);//利用buffer处理流处理文件
osFileName.write(file.getName().getBytes());//将文件后缀长度+名字发送出去
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) != -1){
os.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bis != null)
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(os != null)
os.close();
osFileName.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(socket != null)
socket.close();
socket1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void server() {
Socket socket = null;
InputStream is = null;
BufferedOutputStream bos = null;
Socket socket1 = null;
ServerSocket serverSocket = null;
InputStream isFileName = null;
try {
serverSocket = new ServerSocket(9999);//输入端口号
socket = serverSocket.accept();//接受文件名的套接字
socket1 = serverSocket.accept();//接受文件的套接字
isFileName = socket.getInputStream();//接收文件名的输入流
is = socket1.getInputStream();//接收文件名的输入流
//接收文件名字
byte[] buffer = new byte[1024];
int len;
String fileName = null;
while ((len = isFileName.read(buffer)) != -1) {
fileName = new String(buffer,0,len);
}
//接收的文件的后缀名长度:
int i = fileName.lastIndexOf(".");
//接收文件的名称
String beginFileName = fileName.substring(0,i);
//接收文件的后缀名
String endFileName = fileName.substring(i);
//创建输出流用来接收文件
bos = new BufferedOutputStream(new FileOutputStream(beginFileName+"(服务器接收)"+endFileName));
while ((len = is.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
System.out.println("接收的来自"+socket.getInetAddress().getHostAddress() + "传输的 " + beginFileName + endFileName +" 成功");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(bos != null)
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(isFileName != null)
isFileName.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(socket != null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(socket1 != null)
socket1.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(serverSocket != null)
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
例子3:客户端发送文件给服务端,服务端将文件保存在本地,服务器给客户端反馈
import org.junit.Test;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPTest3 {
@Test
public void client(){
Socket socket = null;
Socket socket1 = null;
OutputStream os = null;
OutputStream osFileName = null;
BufferedInputStream bis = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
socket = new Socket(InetAddress.getLocalHost().getHostAddress(),9999);
socket1 = new Socket(InetAddress.getLocalHost().getHostAddress(),9999);
osFileName = socket.getOutputStream();//存放文件名字
os = socket1.getOutputStream();//存放文件
File file = new File("伊蕾娜1.jpg");//此处填写文件名
FileInputStream fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);//利用buffer处理流处理文件
osFileName.write(file.getName().getBytes());//将文件后缀长度+名字发送出去
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) != -1){
os.write(buffer,0,len);
}
//关闭数据的输出
socket.shutdownOutput();
socket1.shutdownOutput();
//接收来自服务器端的数据
is = socket1.getInputStream();
baos = new ByteArrayOutputStream();
byte[] buffer1 = new byte[20];
int len1;
while ((len1 = is.read(buffer1)) != -1){
baos.write(buffer1,0,len1);
}
System.out.println("发送给"+socket1.getInetAddress().getHostAddress()+"的"+baos.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bis != null)
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(os != null)
os.close();
osFileName.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(socket != null)
socket.close();
socket1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void server() {
Socket socket = null;
InputStream is = null;
BufferedOutputStream bos = null;
Socket socket1 = null;
ServerSocket serverSocket = null;
InputStream isFileName = null;
OutputStream os = null;
try {
serverSocket = new ServerSocket(9999);//输入端口号
socket = serverSocket.accept();//接受文件名的套接字
socket1 = serverSocket.accept();//接受文件的套接字
isFileName = socket.getInputStream();//接收文件名的输入流
is = socket1.getInputStream();//接收文件名的输入流
//接收文件名字
byte[] buffer = new byte[1024];
int len;
String fileName = null;
while ((len = isFileName.read(buffer)) != -1) {
fileName = new String(buffer,0,len);
}
//接收的文件的后缀名长度:
int i = fileName.lastIndexOf(".");
//接收文件的名称
String beginFileName = fileName.substring(0,i);
//接收文件的后缀名
String endFileName = fileName.substring(i);
//创建输出流用来接收文件
bos = new BufferedOutputStream(new FileOutputStream(beginFileName+"(服务器接收)"+endFileName));
while ((len = is.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
System.out.println("已接收来自"+socket1.getInetAddress().getHostAddress() + "传输的 " + beginFileName + endFileName +" 文件");
//向客户端发送反馈
os = socket1.getOutputStream();
os.write("文件已接收成功".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(bos != null)
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(os != null)
os.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(isFileName != null)
isFileName.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(socket != null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(socket1 != null)
socket1.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(serverSocket != null)
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
UDP网络编程
import org.junit.Test;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.util.Date;
public class UDPTest1 {
@Test
public void sender(){
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
String str = "我是UDP方式发送的一段文字";
byte[] data = str.getBytes();
InetAddress inet = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,7777);
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null)
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void receiver(){
DatagramSocket socket = null;
try {
socket = new DatagramSocket(7777);
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()));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null)
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
URL编程
(URL-----种子)
import java.net.MalformedURLException;
import java.net.URL;
public class URLTest1 {
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:8080/examples/beauty.jpg?username=Tom");
System.out.println(url.getProtocol());//协议名:http
System.out.println(url.getHost());//主机名:localhost
System.out.println(url.getPort());//端口号:8080
System.out.println(url.getPath());//文件路径:/examples/beauty.jpg
System.out.println(url.getFile());//文件名:/examples/beauty.jpg?username=Tom
System.out.println(url.getQuery());//查询名:username=Tom
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}