Detailed explanation of the use of Java network programming
#TCP/IP Network Mode
| |||||||||||||||||||||||||||||||||||||
Application layerSuch as HTTP, FTP, DNS | |||||||||||||||||||||||||||||||||||||
Transport layersuch as TCP, UDP | |||||||||||||||||||||||||||||||||||||
network layersuch as IP, ICMP, IGMP
| |||||||||||||||||||||||||||||||||||||
Chainsaw layerSuch as driver, interface |
#Method declaration | |||||||||||||||||||||||||||||||||||||
InetAddress getAddress() | |||||||||||||||||||||||||||||||||||||
int getPort() | |||||||||||||||||||||||||||||||||||||
byte[] getData() | |||||||||||||||||||||||||||||||||||||
int getLength() | |||||||||||||||||||||||||||||||||||||
#Method declaration | |||||||||||||||||||||||||||
void receive(DatagramPacket p) | |||||||||||||||||||||||||||
void send(DatagramPacket p) | |||||||||||||||||||||||||||
void close() | |||||||||||||||||||||||||||
ServerSocket类中的常用方法 | |
方法声明 | 功能描述 |
Socket accept() | 该方法用于等待客户端的连接,在客户端连接之前一直处于阻塞状态,如果有客户端连接就会返回一个与之对应的Socket对象 |
InetAddress getInetAddress() | 该方法用于返回一个InetAddress对象,该对象封装了ServerSocket绑定的IP地址 |
boolean isClosed() | 该方法用于判断ServerSocket对象是否为关闭状态,如果是关闭状态则返回true,反之则返回false |
void bind(SocketAddress endpoint) | 该方法用于判断ServerSocket对象绑定到指定的IP地址和端口号,其中参数endpoint封装了IP地址和端口号。 |
2、Socket
Socket类中的常用方法 | |
方法声明 | 功能描述 |
int getPort() | 该方法返回一个int类型对象,该对象时Socket对象与服务器端连接的端口号 |
InetAddress getLocalAddress() | 该方法用于获取Socket对象绑定的本地IP地址,并将IP地址封装成InetAddress类型的对象返回 |
void close() | 该方法用于关闭Socket连接,结束本次通信。在关闭Socket之前,应将于Socket相关的所有的输入与输出流全部关闭,这是因为一个良好的程序应该在执行完毕时释放所有的资源 |
IputStream getInputStream() | 该方法返回一个InputStream类型的输入流对象,如果该对象是由服务器端的Socket返回,就用于读取客户端发送的数据,反之,用于读取服务器端发送的数据 |
OutputStream getOutputStream() | 该方法返回一个OutputStream类型的输出流对象,如果该对象是由服务器端的Socket返回,就用于向客户端发送数据,反之,用于向服务器端发送数据 |
1 import java.io.OutputStream; 2 import java.net.ServerSocket; 3 import java.net.Socket; 4 5 public class Example4 { 6 public static void main(String[] args) throws Exception { 7 new TCPServer().listen(); //创建TCPServer对象,并调用listen()方法 8 } 9 } 10 //TCP服务器端 11 class TCPServer{ 12 private static final int PORT= 7788;//定义一个端口号 13 14 public void listen() throws Exception{ //定义一个listen()方法,抛出一个异常 15 ServerSocket serverSocket = new ServerSocket(PORT);//创建ServerSocket对象 16 Socket client=serverSocket.accept(); //调用ServerSocket的accept()方法接收数据 17 OutputStream os = client.getOutputStream(); //获取客户端的输出流 18 System.out.println("开始与客户端交换数据"); 19 os.write(("Java欢迎你!").getBytes()); 20 Thread.sleep(5000); //模拟执行其他功能占用的时间 21 System.out.println("结束与客户端交互数据"); 22 os.close(); 23 client.close(); 24 } 25 }
1 import java.io.InputStream; 2 import java.net.InetAddress; 3 import java.net.Socket; 4 5 public class Example5 { 6 public static void main(String[] args) throws Exception{ 7 new TCPClient().connect();//创建TCPClient对象,并调用connect()方法 8 } 9 } 10 //TCP客户端 11 class TCPClient{ 12 private static final int PORT=7788;//服务端的端口号 13 public void connect() throws Exception{ 14 //创建一个Socket并连接到给出地址和端口号的计算机 15 Socket client = new Socket(InetAddress.getLocalHost(),PORT); 16 InputStream is = client.getInputStream(); //得到接收数据的流 17 byte[] buf = new byte[1024]; //定义1024个字节数组的缓冲区 18 int len=is.read(buf); //将数据读取到缓冲区中 19 System.out.println(new String(buf,0,len)); //将缓冲区中的数据输出 20 client.close(); //关闭Socket对象,释放资源 21 } 22 }
Example4 运行结果: 开始与客户端交换数据 结束与客户端交互数据 Example5 运行结果: Java欢迎你!
4、TCP案例——文件上传
实现图片上传到服务器的功能。
服务端程序:
1 import java.io.File; 2 import java.io.FileOutputStream; 3 import java.io.InputStream; 4 import java.io.OutputStream; 5 import java.net.ServerSocket; 6 import java.net.Socket; 7 8 public class Example7 { 9 public static void main(String[] args) throws Exception{ 10 ServerSocket serverSocket = new ServerSocket(10001);//创建ServerSocket对象 11 while (true){ 12 //调用accept()方法接收客户端请求,得到Socket对象 13 Socket s = serverSocket.accept(); 14 //每当和客户端建立Socket连接后,单独开启一个线程处理和客户端的交互 15 new Thread(new ServerThread(s)).start(); 16 } 17 } 18 } 19 class ServerThread implements Runnable{ 20 private Socket socket ; //持有一个Socket类型的属性 21 public ServerThread(Socket socket){ //构造方法中吧Socket对象作为实参传入 22 this.socket=socket; 23 } 24 25 @Override 26 public void run() { 27 String ip = socket.getInetAddress().getHostAddress(); //获取客户端的IP地址 28 int count =1; //上传图片个数 29 try{ 30 InputStream in = socket.getInputStream(); 31 //创建上传图片目录的File对象 32 File parentFile =new File("/Users/adims/Downloads/upload/"); 33 if (!parentFile.exists()){ //如果不存在,就创建这个目录 34 parentFile.mkdir(); 35 } 36 //把客户端的IP地址作为上传出文件的文件名 37 File file = new File(parentFile,ip+"("+count+").jpeg"); 38 while (file.exists()){ 39 //如果文件名存在,则把count++ 40 file=new File(parentFile,ip+"("+(count++)+").jpeg"); 41 } 42 //创建FileOutputStream对象 43 FileOutputStream fos = new FileOutputStream(file); 44 byte[] buf=new byte[1024]; //定义一个字节数组 45 int len=0; //定义一个int类型的变量len,初始值为0 46 while ((len=in.read(buf))!=-1){ //循环读取数据 47 fos.write(buf,0,len); 48 } 49 OutputStream out = socket.getOutputStream(); //获取服务端的输出流 50 out.write(("上传成功").getBytes()); //上传成功后向客户端写出"上传成功" 51 fos.close(); //关闭输出流对象 52 socket.close(); //关闭Socket对象 53 }catch (Exception e){ 54 throw new RuntimeException(e); 55 } 56 } 57 }
客户端程序:
1 import java.io.FileInputStream; 2 import java.io.InputStream; 3 import java.io.OutputStream; 4 import java.net.InetAddress; 5 import java.net.Socket; 6 7 public class Example8 { 8 public static void main(String[] args) throws Exception{ 9 Socket socket= new Socket(InetAddress.getLocalHost(),10001); //创建客户端Socket对象,指定IP地址和端口号 10 OutputStream out= socket.getOutputStream(); //获取Socket的输出流对象 11 //创建FileInputStream对象 12 FileInputStream fis = new FileInputStream("/Users/adims/Downloads/WechatIMG1.jpeg"); 13 byte[] buf =new byte[1024]; //定义一个字节数组 14 int len; //定义一个int类型的变量len 15 while ((len=fis.read(buf))!=-1){ //循环读取数据 16 out.write(buf,0,len); 17 } 18 socket.shutdownOutput(); //关闭客户端输出流 19 InputStream in = socket.getInputStream(); //获取Socket的输入流对象 20 byte[] bufMsg = new byte[1024]; //定义一个字节数组 21 int num =in.read(bufMsg); //接收服务端的信息 22 String Msg = new String(bufMsg,0,num); 23 System.out.println(Msg); 24 fis.close(); //关闭输入流对象 25 socket.close(); //关闭Socket对象 26 } 27 }
需注意:shutdownOutput()方法非常重要,因为服务器端程序在while循环中读取客户端发送的数据,当读取到-1时才会结束循环,如果客户端不调用shutdownOutput()方法关闭输出流,服务器端就不会读到-1,而会一直执行while循环,同时客户端服务器端的read(byte[])方法也是一个阻塞方法,这样客户端与服务器端进入一个“死锁”状态。
The above is the detailed content of Detailed explanation of the use of Java network programming. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools