In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
What is the usage of Socket in Java? I believe many inexperienced people don't know what to do about it. Therefore, this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
1 the problem introduces 1.1 network architecture model
The network architecture model mainly includes OSI reference model and TCP/IP five-layer model.
1.1.1 OSI reference model
OSI (Open System Interconnect), that is, open systems interconnection. Commonly known as the OSI reference model, it is a network interconnection model studied by ISO (International Organization for Standardization) in 1985. In order to make network applications more popular, ISO has launched the OSI reference model, so that all companies specify their own networks according to a unified standard, so that they can interconnect with each other.
OSI defines the seven-layer framework of network interconnection (physical layer, data link layer, network layer, transport layer, session layer, presentation layer, application layer).
1.1.2 TCP/IP five-tier model
TCP/IP five-layer protocol (physical layer, data link layer, network layer, transport layer, application layer)
1.1.3 description of each protocol layer application layer
The layer closest to the user in the application layer is not only to provide computer users with application interfaces, but also to provide users with a variety of network services directly. Our common application layer network service protocols are: HTTP,HTTPS,FTP,TELNET and so on.
Transport layer
The end-to-end link of the host is established, and the role of the transport layer is to provide end-to-end reliable and transparent data transmission services for the upper layer protocols, including dealing with error control and flow control. This layer shields the details of the lower layer data communication to the upper layer, so that the high-level users can only see a host-to-host reliable data path that can be controlled and set by the user between the two transmission entities. As we usually say, TCP UDP is on this floor. The port number is both the "end" here.
Network layer
This layer establishes the connection between the two nodes through IP addressing, selects the appropriate routing and switching nodes for the packets sent by the transport layer of the source side, and correctly transmits them to the transport layer of the destination side according to the address. It is commonly known as the IP layer. This layer is what we often call the IP protocol layer. IP protocol is the foundation of Internet.
1.2 problems in network programming
The common problem in network programming is how to locate one or more hosts on the network, and the other is how to transmit data after positioning. For the former, in the network layer, it is mainly responsible for the location of the network host and the routing of data transmission. A host on the Internet can be uniquely determined by the IP address. For the latter, application-oriented reliable (tcp) or unreliable (UDP) data transmission mechanisms are provided in the transport layer.
For the client / server (Cramp S) structure. That is, both sides of the communication wait for the client to make a request and respond as a server. The customer applies to the server when the service is needed. The server generally runs as a daemon all the time, listening to the network port, and once there is a customer request, it will start a service process to respond to the customer, and at the same time, it will continue to monitor the service port, so that the later customers can also get the service in time.
For the browser / server (Bramp S) structure. The customer makes a request to the server when the service is needed. The server returns in time after responding, and there is no need to listen to the port in real time.
1.3 TCP Protocol and UDP Protocol 1.3.1 TCP
TCP, which stands for Tranfer Control Protocol, is a connection-oriented protocol that ensures reliable transmission. Through the TCP protocol transmission, the result is a sequential error-free data stream. A connection must be established between the two pairs of socket of the sender and receiver. When one socket (usually the server socket) is waiting to establish a connection, the other socket can request a connection. Once the two socket are connected, they can carry out two-way data transmission, and both sides can send or receive.
TCP's three-way handshake
Establishing a TCP connection requires a "three-way handshake": the first handshake: the client sends the syn packet (syn=j) to the server, and enters the SYN_SEND state, waiting for the server to confirm; the second handshake: the server receives the syn packet and must confirm the customer's SYN (ack=j+1). At the same time, it also sends a SYN packet (syn=k), that is, the SYN+ACK packet, when the server enters the SYN_RECV state. The third handshake: the client receives the SYN+ACK packet from the server and sends the confirmation packet ACK (ack=k+1) to the server. After the packet is sent, the client and the server enter the ESTABLISHED state and complete the three-way handshake.
The packet transmitted during the handshake does not contain data, and it is only after the three-way handshake that the client and the server officially begin to transmit data. Ideally, once a TCP connection is established, the TCP connection will be maintained until either of the communicating parties actively closes the connection. When disconnected, both the server and the client can initiate a request to disconnect the TCP.
1.3.2 UDP
UDP is the abbreviation of (User Datagram Protocol), which is a connectionless protocol. Each Datagram is an independent information, including a complete source address or destination address, which is transmitted to the destination by any possible path on the network, so whether it can reach the destination, the time of arrival and the correctness of the content can not be guaranteed.
1.3.3 the difference between TCP and UDP UDP:
1. Complete address information is given in each Datagram, so there is no need to establish a connection between the sender and the receiver.
2. UDP has a size limit when transmitting data, and each Datagram to be transmitted must be limited to 64KB.
3. UDP is an unreliable protocol, and the datagrams sent by the sender do not necessarily arrive at the receiver in the same order.
TCP:
1. Connection-oriented protocol, it is necessary to establish a connection before data transmission between socket, so connection time is needed in TCP.
2. There is no limit on the size of the data transmitted by TCP. Once the connection is established, the socket of both sides can transmit large data in a unified format.
3. TCP is a reliable protocol that ensures that the receiver correctly acquires all the data sent by the sender.
Application:
1. TCP has strong vitality in network communication, for example, remote connection (Telnet) and file transfer (FTP) require data of indefinite length to be transmitted reliably. But reliable transmission comes at a price, and the verification of the correctness of data content will inevitably take up the processing time of the computer and the bandwidth of the network, so the efficiency of TCP transmission is not as high as UDP.
2. UDP is easy to operate and requires less monitoring, so it is usually used in client/server applications in distributed systems with high reliability in local area networks. For example, the video conference system does not require the audio and video data to be absolutely correct, as long as it is consistent. In this case, it is obviously more reasonable to use UDP.
2 socket Network programming 2.1.What is socket?
The original meaning of Socket is "hole" or "socket". In network programming, two programs on the network exchange data through a two-way communication connection, one end of which is called a socket.
Socket socket is the cornerstone of communication and the basic operation unit of network communication that supports TCP/IP protocol. It is the abstract representation of the endpoint in the process of network communication, and contains five kinds of information necessary for network communication: the protocol used for the connection, the IP address of the local host, the protocol port of the local process, the IP address of the remote host, and the protocol port of the remote process.
Socket is essentially a programming interface (API), which encapsulates TCP/IP. TCP/IP should also provide an interface for programmers to do network development, which is the Socket programming interface; HTTP is a car, which provides a specific form of encapsulating or displaying data; and Socket is an engine that provides the ability of network communication.
2.2 the principle of Socket
Socket essentially provides endpoints for process communication. Before process communication, both parties must first create an endpoint, otherwise there is no way to establish contact and communicate with each other. Just as both parties must own a telephone before making a phone call.
The connection process between sockets can be divided into three steps: server monitoring, client request, and connection confirmation.
1. Server monitoring: server-side sockets do not locate specific client sockets, but are waiting for a connection to monitor the network status in real time.
2. Client request: refers to the connection request made by the socket of the client, and the target of the connection is the socket on the server side. To do this, the client socket must first describe the socket of the server it wants to connect to, indicate the address and port number of the server-side socket, and then make a connection request to the server-side socket.
3. Connection confirmation: when the server socket monitors or receives the connection request of the client socket, it responds to the request of the client socket and establishes a new thread to send the description of the server socket to the client. Once the client confirms this description, the connection is established. The server-side socket continues to listen and continues to receive connection requests from other client sockets.
3 realization of socket network programming based on java
The Listen on the Server side listens to whether there is a connection request on a port, the client side sends a connection request to the Server side, and the server sends back an Accept acceptance message to the Client side. Such a connection is established. Both Server and client can communicate with each other through Send,Write and other methods.
For a fully functional Socket, it should include the following basic structure, and its working process includes the following four basic steps:
1. Create a Socket
2. Open the input / outflow connected to the Socket
3. Read / write Socket according to certain protocols
4. Close Socket.
3.1 socket implementation based on TCP
SocketClient.java
Public class SocketClient {public static void main (String [] args) throws InterruptedException {try {/ / and server creation connection Socket socket = new Socket ("localhost", 8088) / / messages to be sent to the server OutputStream os = socket.getOutputStream (); PrintWriter pw = new PrintWriter (os); pw.write ("client sends messages"); pw.flush () Socket.shutdownOutput (); / / Information received from the server InputStream is = socket.getInputStream (); BufferedReader br = new BufferedReader (new InputStreamReader (is)); String info = null While ((info = br.readLine ())! = null) {System.out.println ("I am the client, the server returns information:" + info);} br.close (); is.close () Os.close (); pw.close (); socket.close ();} catch (Exception e) {e.printStackTrace ();}
SocketServer.java
Public class SocketServer {public static void main (String [] args) {try {/ / create server socket ServerSocket serverSocket = new ServerSocket (8088); / / create client socket Socket socket = new Socket () / / Loop listening waiting for client connection while (true) {/ / listening client socket = serverSocket.accept (); ServerThread thread = new ServerThread (socket) Thread.start (); InetAddress address=socket.getInetAddress (); System.out.println ("IP of current client:" + address.getHostAddress ());} catch (Exception e) {/ / TODO: handle exception e.printStackTrace () }
ServerThread.java
Public class ServerThread extends Thread {private Socket socket = null; public ServerThread (Socket socket) {this.socket = socket;} @ Override public void run () {InputStream is=null; InputStreamReader isr=null; BufferedReader br=null; OutputStream os=null; PrintWriter pw=null Try {is = socket.getInputStream (); isr = new InputStreamReader (is); br = new BufferedReader (isr); String info = null While ((info=br.readLine ())! = null) {System.out.println ("I am the server, the client says:" + info);} socket.shutdownInput () Os = socket.getOutputStream (); pw = new PrintWriter (os); pw.write ("Server Welcome"); pw.flush () } catch (Exception e) {/ / TODO: handle exception} finally {/ / close the resource try {if (pwelled null) pw.close (); if (ossified null) os.close () If (brushing null) br.close (); if (isringing null) isr.close (); if (isometric null) is.close (); if (socketpacking null) socket.close () } catch (IOException e) {e.printStackTrace ();}
At run time, executing SocketClient first will indicate that you cannot connect to the server because no service is listening on port 8088 at this time. This demo is a multithreaded implementation. After starting SocketServer first, the server will listen to port 8088 all the time, and then execute SocketClient to output the result normally.
3.2 socket implementation based on UDP
SocketClient.java
Public class SocketClient {public static void main (String [] args) {try {/ / messages to be sent String sendMsg = "messages sent by the client"; / / get the address of the server InetAddress addr = InetAddress.getByName ("localhost") / / create a packet package object that encapsulates the packet data to be sent and the server address and port number DatagramPacket packet = new DatagramPacket (sendMsg.getBytes (), sendMsg.getBytes (). Length, addr, 8088); / / create a Socket object DatagramSocket socket = new DatagramSocket () / / send messages to server socket.send (packet); / / close socket socket.close ();} catch (Exception e) {/ / TODO Auto-generated catch block e.printStackTrace ();}
SocketServer.java
Public class SocketServer {public static void main (String [] args) {try {/ / message to be received byte [] bytes = new byte [1024]; DatagramPacket packet = new DatagramPacket (bytes, bytes.length) / / create socket and specify port DatagramSocket socket = new DatagramSocket (8088); / / receive data sent by socket client. If it is not received, socket.receive (packet) will be blocked consistently; String receiveMsg = new String (packet.getData (), 0recom packet.getLength ()); System.out.println (packet.getLength ()); System.out.println (receiveMsg) / / close socket socket.close ();} catch (Exception e) {/ / TODO: handle exception e.printStackTrace ();}
When running, start SocketServer first, and then start SocketClient, and the data will be printed normally. When SocketServer is started first, the code is consistently blocked here when it reaches socket.receive (packet), until after SocketClient is started, SocketServer continues to execute and prints out the information received by SocketClient. If you start SocketClient first, the execution will finish immediately, and when you execute SocketServer, it will still block at the receive method until the next SocketClient execution.
After reading the above, have you mastered the usage of Socket in Java? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.