search
HomeJavajavaTutorialDetailed explanation of Socket network programming

Detailed explanation of Socket network programming

Jun 27, 2017 am 10:24 AM
socketnetwork programming

java.net.InetAddress Class: This class represents an Internet Protocol (IP) address.

Static method:
static InetAddress getLocalHost() returns the local host (your own computer).
static InetAddress getByName(String host) Determines the IP address of a host given a hostname.
Non-static methods:
String getHostAddress() Returns the IP address string (in text representation).
String getHostName() Gets the host name of this IP address.


The receiving end of UDP communication: receives the datagram packet sent by the sending end and unpacks it
* Classes related to udp:
* java.net.DatagramPacket: This class represents data Report package.
* Function: Use datagram packets to receive data from the sender
* java.net.DatagramSocket: This class represents a socket used to send and receive datagram packets.
* Function: Send datagram packets, receive datagram packets
* Socket: Network object binding IP address and port number
*
* Construction method:
* DatagramPacket( byte[] buf, int length)
* Construct DatagramPacket to receive data packets with length length.
* DatagramSocket(int port)
* Creates a datagram socket and binds it to the specified port on the local host.
*
* Member methods:
* void receive(DatagramPacket p) Receives a datagram packet from this socket.
*
* Implementation steps:
* 1. Create a DatagramPacket object and receive the datagram from the sender
* 2. Create a DatagramSocket object and match it with the port number to be specified by the system
* 3. Use the method receive in DatagramSocket to receive the datagram packet from the sender
* 4. Unpacking
* DatagramPacket has methods related to datagram packets
* int getLength() Get the length of the sender's data
* InetAddress getAddress() Gets the IP address object of the sender
* int getPort() Gets the port number of the sender (randomly assigned by the system)
* 5. Release resources

 1 public static void main(String[] args) throws IOException { 2         //1.创建DatagramPacket对象,接收发送端的数据报 3         byte[] bytes = new byte[1024];//数据最大传输64kb  1024*64 4         DatagramPacket dp = new DatagramPacket(bytes, bytes.length); 5         //2.创建DatagramSocket对象,并且和系统要指定的端口号 6         DatagramSocket ds = new DatagramSocket(8888); 7         //3.使用DatagramSocket中的方法receive发送端接收数据报包 8         ds.receive(dp); 9         //4.拆包10         //int getLength()  获取发送端数据的长度11         int length = dp.getLength();12         //InetAddress getAddress() 获取发送端的IP地址对象13         String ip = dp.getAddress().getHostAddress();14         //int getPort()  获取发送端的端口号(系统随机分配的)15         int port = dp.getPort();16         17         System.out.println(new String(bytes,0,length)+"ip:"+ip+",端口号"+port);18         //5.释放资源19         ds.close();20     }

The sending end of UDP communication: Pack the data and send the datagram packet according to the IP address and port of the receiving end.
*
* Classes related to UDP:
* java.net.DatagramPacket: This type of representation Datagram packet.
* Function: Pack the data and the IP address and port number of the receiving end
* java.net.DatagramSocket: This class represents the socket used to send and receive datagram packets.
* Function: Send datagram packets, receive datagram packets
* Socket: Network object binding IP address and port number
*
* Construction method:
* DatagramPacket( byte[] buf, int length, InetAddress address, int port)
* Construct a datagram packet, which is used to send a packet of length length to the specified port number on the specified host.
* DatagramSocket()
* Constructs a datagram socket and binds it to any available port on the local host.
*
* Member methods:
* void send(DatagramPacket p) Sends a datagram packet from this socket.
*
* Implementation steps:
* 1. Create a DatagramPacket object, encapsulate the data and the IP address and port number of the receiving end (create a container)
* 2. Create a DatagramSocket object (create a dock)
* 3. Use the method send in DatagramSocket to send datagram packets
* 4. Release resources
*
* UDP communication is for connectionless: data can be sent regardless of whether there is a receiving end or not. Data loss will occur at the receiving end

 1 public static void main(String[] args) throws IOException { 2         //1.创建DatagramPacket对象,封装数据和接收端的IP地址,端口号(创建集装箱) 3         byte[] bytes = "你好UDP!".getBytes(); 4         InetAddress address = InetAddress.getByName("127.0.0.1"); 5         DatagramPacket dp = new DatagramPacket(bytes, bytes.length, address, 8888); 6         //2.创建DatagramSocket对象(创建码头) 7         DatagramSocket ds = new DatagramSocket(); 8         //3.使用DatagramSocket中的方法send发送数据报包 9         ds.send(dp);10         //4.释放资源11         ds.close();12     }

Client of TCP communication: sends a request connection to the server and receives data written back by the server
*
* Represents the client's class:
* java.net.Socket: This class implements client sockets (it can also be called "sockets").
*
* Constructor:
* Socket(InetAddress address, int port) Creates a stream socket and connects it to the specified port number of the specified IP address.
* Socket(String host, int port) Creates a stream socket and connects it to the specified port number on the specified host.
*
* Member methods:
* OutputStream getOutputStream() Returns the output stream of this socket.
* InputStream getInputStream() Returns the input stream of this socket.
*
* Note: For data interaction between the client and the server, you cannot use the stream object created by yourself. You must use the stream provided in Socket
*
* Implementation steps:
* 1. Create a client Socket object and bind the IP address and port number of the server
* 2. Use the method getOutputStream in the Socket to obtain the network output stream
* 3. Use the method write in the OutputStream network stream to send data to the server
* 4. Use the method getInputStream in Socket to obtain the network input stream
* 5. Use the method read in the InputStream network stream to read the data written back by the server
* 6. Release resources
*
* Note: TCP is connection-oriented communication. The server must be started first. After starting the client, if the server is not started
* , ConnectException will be thrown: Connection refused: connect

 1 public static void main(String[] args) throws IOException { 2         //1.创建客户端Socket对象,绑定服务器的IP地址和端口号 3         Socket socket = new Socket("127.0.0.1", 9999); 4         //2.使用Socket中的方法getOutputStream获取网络输出流 5         OutputStream os = socket.getOutputStream(); 6         //3.使用OutputStream网络流中的方法write给服务器发送数据 7         os.write("你好服务器".getBytes()); 8         //4.使用Socket中的方法getInputStream获取网络输入流 9         InputStream is = socket.getInputStream();10         //5.使用InputStream网络流中的方法read读取服务器回写的数据11         byte[] bytes = new byte[1024];12         int len = is.read(bytes);13         System.out.println(new String(bytes,0,len));14         //6.释放资源15         socket.close();16     }

TCP通信的服务器端:接收客户端的发送的数据,给客户端回写数据
*
* 表示服务器的类:
* java.net.ServerSocket:此类实现服务器套接字。
*
* 构造方法:
* ServerSocket(int port) 创建绑定到特定端口的服务器套接字。
*
* 有一件特别重要的事:服务器必须的知道是哪个客户端请求的服务器
* 所有可以使用accept方法获取请求的客户端
* 成员方法:
* Socket accept() 侦听并接受到此套接字的连接。
*
* 实现步骤:
* 1.创建ServerSocket对象,和系统要指定的端口号
* 2.使用ServerSocket中的方法accept获取请求的客户端对象
* 3.使用Socket中的方法getInputStream获取网络输入流
* 4.使用InputStream网络流中的方法read读取客户端发送的数据
* 5.使用Socket中的方法getOutputStream获取网络输出流
* 6.使用OutputStream网络流中的方法write给客户端回写数据
* 7.释放资源(ServerSocket,Socket)

 1 public static void main(String[] args) throws IOException { 2         //1.创建ServerSocket对象,和系统要指定的端口号 3         ServerSocket server = new ServerSocket(9999); 4         //2.使用ServerSocket中的方法accept获取请求的客户端对象 5         Socket socket = server.accept(); 6         //3.使用Socket中的方法getInputStream获取网络输入流 7         InputStream is = socket.getInputStream(); 8         byte[] bytes = new byte[1024]; 9         //4.使用InputStream网络流中的方法read读取客户端发送的数据10         int len = is.read(bytes);11         System.out.println(new String(bytes,0,len));12         //5.使用Socket中的方法getOutputStream获取网络输出流13         OutputStream os = socket.getOutputStream();14         //6.使用OutputStream网络流中的方法write给客户端回写数据15         os.write("收到".getBytes());16         //7.释放资源(ServerSocket,Socket)17         socket.close();18         server.close();19     }

 

The above is the detailed content of Detailed explanation of Socket network programming. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

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...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

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...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

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...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

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

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

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 default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software