In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "how to understand Java socket programming". In the operation of practical cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Introduction
Socket, also known as "socket", is used to describe the address and port of IP and is the handle of a communication chain; at the same time, socket communication is based on a transport mode on the TCP/IP network layer, and we usually refer to TCP and UDP as the transport layer. Let's take you to know it through the basic principles and examples of socket communication.
Basic principles of socket Communication
As mentioned above, socket communication is based on the TCP/IP protocol and belongs to the transport layer protocol, as shown in the following figure:
At the same time, socket is based on an abstraction between application service and TCP/IP communication. It distributes the complex communication logic in TCP/IP protocol. For users, the network connection can be realized through a set of simple API. First, the server initializes the ServerSocket, then binds the specified port, and then listens to the port and blocks it by calling the accept method. In this case, if the client has a socket connected to the server, the server can connect with the client through the listening and accept methods. As shown in the following figure:
Basic example
Server side: listen to a port and wait for the connection to arrive
Import java.io.InputStream
Import java.net.ServerSocket
Import java.net.Socket
Public class SocketServer {
Public static void main (String [] args) throws Exception {
/ / listen on the specified port
Int port = 55533
ServerSocket server = new ServerSocket (port)
/ / server will be waiting for the arrival of the connection
System.out.println ("server will be waiting for the connection to arrive")
Socket socket = server.accept ()
/ / after the connection is established, get the input stream from socket and set up a buffer to read it.
InputStream inputStream = socket.getInputStream ()
Byte [] bytes = new byte [1024]
Int len
StringBuilder sb = new StringBuilder ()
While ((len = inputStream.read (bytes))! =-1) {
/ / Note to specify the encoding format. The sender and receiver must be unified. It is recommended to use UTF-8.
Sb.append (new String (bytes, 0, len, "UTF-8"))
}
System.out.println ("get message from client:" + sb)
InputStream.close ()
Socket.close ()
Server.close ()
}
}
Client: connect to the specified server through ip and port, then get the output stream through Socket and output to it, and the server will get the message. The final server console prints messages
Import java.io.OutputStream
Import java.net.Socket
Public class SocketClient {
Public static void main (String args []) throws Exception {
/ / IP address and port of the server to be connected
String host = "127.0.0.1"
Int port = 55533
/ / establish a connection with the server
Socket socket = new Socket (host, port)
/ / get the output stream after establishing the connection
OutputStream outputStream = socket.getOutputStream ()
String message= "Hello"
Socket.getOutputStream () .write (message.getBytes ("UTF-8"))
OutputStream.close ()
Socket.close ()
}
}
The above example is an example of sending a message one-way, usually a question-and-answer, two-way. Please refer to the following examples:
Two-way communication-server: what is different from the above is that when the client's message is read, the output stream is opened and the specified message is sent back to the client
Import java.io.InputStream
Import java.io.OutputStream
Import java.net.ServerSocket
Import java.net.Socket
Public class SocketServer {
Public static void main (String [] args) throws Exception {
/ / listen on the specified port
Int port = 55533
ServerSocket server = new ServerSocket (port)
/ / server will be waiting for the arrival of the connection
System.out.println ("server will be waiting for the connection to arrive")
Socket socket = server.accept ()
/ / after the connection is established, get the input stream from socket and set up a buffer to read it.
InputStream inputStream = socket.getInputStream ()
Byte [] bytes = new byte [1024]
Int len
StringBuilder sb = new StringBuilder ()
/ / only when the client closes its output stream can the server get the-1 at the end
While ((len = inputStream.read (bytes))! =-1) {
/ / Note to specify the encoding format. The sender and receiver must be unified. It is recommended to use UTF-8.
Sb.append (new String (bytes, 0, len, "UTF-8"))
}
System.out.println ("get message from client:" + sb)
OutputStream outputStream = socket.getOutputStream ()
OutputStream.write ("Hello Client,I get the message." .getBytes ("UTF-8"))
InputStream.close ()
OutputStream.close ()
Socket.close ()
Server.close ()
}
}
Two-way communication-client side: what is different from the above is that when the message is sent, the method of closing the output stream is called, and then the output stream is opened, waiting for the message from the server.
Import java.io.InputStream
Import java.io.OutputStream
Import java.net.Socket
Public class SocketClient {
Public static void main (String args []) throws Exception {
/ / IP address and port of the server to be connected
String host = "127.0.0.1"
Int port = 55533
/ / establish a connection with the server
Socket socket = new Socket (host, port)
/ / get the output stream after establishing the connection
OutputStream outputStream = socket.getOutputStream ()
String message = "Hello yiwangzhibujian"
Socket.getOutputStream () .write (message.getBytes ("UTF-8"))
/ / data has been sent through the shutdownOutput high-speed server, and data can only be accepted later.
Socket.shutdownOutput ()
InputStream inputStream = socket.getInputStream ()
Byte [] bytes = new byte [1024]
Int len
StringBuilder sb = new StringBuilder ()
While ((len = inputStream.read (bytes))! =-1) {
/ / Note to specify the encoding format. The sender and receiver must be unified. It is recommended to use UTF-8.
Sb.append (new String (bytes, 0, len, "UTF-8"))
}
System.out.println ("get message from server:" + sb)
InputStream.close ()
OutputStream.close ()
Socket.close ()
}
}
Matters needing attention
When programming with socket, be careful to tell the other party that the command has been sent, using the following ways:
Method 1: shut down via Socket (Note: after the client Socket is closed, the message sent by the server will not be accepted and the message will not be sent again; if the client wants to send the message again, it needs to create a Socket connection again)
Method 2: the way to close the output stream through Socket
Way 3: through the agreed symbol
Way 4: through a specific length
This is the end of "how to understand Java socket programming". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.