In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
This article shows you how to use the Socket interface in Java, which is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
Detailed explanation of the usage of Socket Interface
In Java, there are two classes to realize network communication based on TCP protocol: the Socket class on the client side and the ServerSocket class on the server side. The function of the ServerSocket class is to establish a Server and listen for the client connection request at any time through the accept () method.
Extend:
Constructors and methods commonly used in ServerSocket
Constructor: ServerSocket (intport) this is a constructor method to listen on a specified port on the default IP address of the current server, that is, to create a ServerSocket object on the specified IP and port
Methods:
Socket accept () blocks and listens on the specified port until a connection request is sent from the client
Void close () closes the current ServerSocket
InetAddressgetInetAddress () returns the native IP address that ServerSocket listens to.
IntgetLocalPort () returns the port number specified on the native IP address that ServerSocket listens to.
IntgetSoTimeout (); void setSoTimeout (int timeout) does not get the corresponding waiting period (TimeOut) during the connection process.
StringtoString () returns the native IP address and its port number of the ServerSocket listener as a string
Constructors and methods commonly used in Socket classes
Constructor: Socket (InetAddressaddress,int port) is used to create a link that sends a connection request to the server-side program on the specified port at the specified IP address
Socket (Stringhost,int port) is the same as above, but this method allows connection requests to be sent to the server through the hostname string
Methods:
Void close () closes the current Socket connection
InetAddressgetInetAddress () returns the IP address of the server to which Socket has established a connection
InputStreamgetInputStream () returns the input stream of the current Socket
OutputStreamgetOutStream () returns the output stream of the current Socket
InetAddressgetLocalAddress () returns the local IP address that connects to the Socket
IntgetLocalPort () returns the local port number that connects to the Socket
Int getPort () returns the port number of the server that established a connection with Socket
IntgetSoTimeOut (); void setSoTimeOut (int timeout) does not get the corresponding waiting period during the connection process.
String toString () returns the attribute information of Socket as a string
The construction methods of the Socket class include the following:
Public Socket (String host,int port)
Public Socket (InetAddress address,int port)
Public Socket (String host,int port,InetAddresslocalAddr,int localPort)
Public Socket (InetAddress host,int port, InetAddress,localAddr,intlocalPort)
Prior to JDK1.1, the Socket class could also be used for TCP/UDP communication:
Public Socket (String host,int port,Booleanstream)
Public Socket (InetAddress host,int port, Booleanstream)
The input / output stream management of the Socket class includes the following methods:
Public InputStream getInputStream ()
Public void shutdowmInput ()
Public OutputStream get OutputStream ()
Public void shutdowmOutput ()
All of these methods will throw IOException exceptions, which need to be caught and handled in the program.
The way to turn off Socket is:
Public void close () throws IOException
The method to set / get Socket data is:
Public InetAddress getInetAddress ()
Public int getPort ()
Public void setSoTimeout (int timeout)
These methods will throw SocketException exceptions that need to be caught and handled in the program.
The construction methods of the ServerSocket class include the following:
Public ServerSocket (int Port)
Public ServerSocket (int Port,int backlog): supports a specified number of connections
Public ServerSocket (int Port,intbacklog,InetAddress bindAddr)
These methods will throw IOException exceptions that need to be caught and handled in the program.
Public Socket accept (): waiting for the client to connect
Public void close (): close Socket
The methods to set / get Socket data include:
Public InetAddress get InetAddress ()
Public int getLocalPort ()
Public void setSoTimeout (int timeout)
These methods will throw SocketException exceptions that need to be caught and handled in the program.
The basic concept of Socket
1. Establish a connection
When a network connection needs to be established, a machine must run a program and wait for the connection at any time, while the program on the other end makes a connection request to it. This is similar to the telephone system, where one party must make a call and the other must wait for the call to be connected. The process of establishing a connection is:
(1) now the server generates a ServerSocket instance object to listen for client connection requests at any time.
(2) when the client needs to connect, a Socket instance object is generated accordingly, and a connection request is issued, where the host parameter indicates the hostname and the port# parameter indicates the port number of the host.
(3) after the server receives the request from the client through the accept () method, it opens up an interface to connect with it and generates the required Imax O data stream.
(4) the communication between the client and the server is carried out through a pair of InputStream and OutputStream. After the end of the communication, both ends shut down the corresponding Socket interface respectively.
two。 Connection address
When making a call, the caller must know the number to be dialed in advance, and the program also needs to know the address or host name when establishing a network connection. In addition, the network connection requires a port number (which can be used as the extension of the phone), and after connecting to the correct host, you need to confirm a specific password for the connection. In some cases, you also need to use an extension number to connect to the network billing system, so there should be a specific port number to connect to the billing program accordingly.
3. Port number
In TCP/IP systems, the port number consists of 16-bit binary integers, that is, between 0 and 65535. In practical applications, the first 1024 port numbers are pre-defined as specific services, so they generally cannot be used unless you want to connect to these servers (such as Telnet,SMTP,mail,ftp, etc.). Before the two programs connect, they must reach an agreement between each other, that is, the client is responsible for initializing the connection, while the server waits for the request at any time. A connection is established only if the client and server specify the same port number. If the port numbers used by the two programs in the system do not match, the connection cannot be established.
4. Network connection mode
In Java, the connection to the TCP/IP interface is implemented by the class in the java.net package. The figure shows how the client and server work during the Socket connection.
Each server port has a port number, which may correspond to multiple port numbers if multiple services are running on a machine. At the end of the communication, both ends shut down the corresponding Socket interface without affecting the other ports.
Basic steps of Socket communication
The basic structure of the program using Socket for network communication is similar, no matter how complete the function of a Socket communication program is and how complex the program is, its basic structure is the same. The process of communicating between the client and the server consists of the following four basic steps:
(1) specify a port number on the server side to wait for the connection, and specify a host and port number on the client side, thus creating Socket/ServerSocket instances on the client side and server side.
(2) Open the input and output stream connected to the Socket.
(3) use input and output streams to read and write Socket according to certain protocols.
(4) close I / O stream and Socket
Usually, the programmer's main work is to program for step (3) of the function to be completed, and step (1), (2) and (4) are almost the same for all communication programs.
Program Design of Socker Communication
1. Server-side program
TCP/IP server-side applications are implemented through two network-related classes, ServerSocket and Socket, provided in the Java language. In addition to establishing a Server, the ServerSocket class provides the ability to listen to client connection requests at any time through the accept () method, which can be constructed in the following two ways.
ServerSocket (int port)
ServerSocket (int port,int backlog)
Where port refers to the port number of the other party in the connection, and backlog represents the maximum number of connections that the server can support. The following program is used to listen to the client application's request to establish a connection and send information to the client after the connection is established.
/ * *
* function: this is a server-side program that listens to client application requests for establishing a connection and sends information to the client after the connection is established
, /
Package com.xushouwei
/ / introduce the corresponding package
Import java.net.*
Import java.io.*
Public class TServer
{
Public static void main (String [] args)
{
/ / define the ServerSocket class
ServerSocket s=null
/ / define the Socket class
Socket s1
/ / define the send string
String sendString= "Hello! this is Xu Shouwei."
/ / get the length of the send string
Int s1lenth=sendString.length ()
/ / define the OutputStream class
OutputStream s1out
/ / define the DataOutputStream class
DataOutputStream dos
/ / establish a connection through port 1314
Try
{
/ / create a ServerSocket and pass in the port number
S=new ServerSocket (1314)
} catch (Exception e)
{
E.printStackTrace ()
}
/ / run the listener in a loop to monitor connection requests
While (true)
{
Try
{
/ / listen for port requests and wait for connection
S1=s.accept ()
/ / get the data flow object connected to socket
S1out=s1.getOutputStream ()
Dos=new DataOutputStream (s1out)
/ / send string
Dos.writeUTF (sendString)
/ / close the data flow (but not close the Socket connection)
Dos.close ()
S1out.close ()
S1.close ()
} catch (Exception e)
{
E.printStackTrace ()
}
}
}
}
two。 Client program
TCP/IP server-side applications are implemented through the Socket class provided in the Java language. Similarly, the Socket class provides many functions, including establishing a network connection, and is constructed in the following ways:
Socket (InetAddress address,int port)
Socket (InetAddress address,int port,Booleanstream)
Socket (String host,int port)
Socket (String host,int port, InetAddresslocalAddr,int localPort)
Where address, host, and port refer to the IP address, host name, and port number of the other party connected, respectively, and stream indicates whether the Socket is a stream-enabled Socket,localAddr and localPort is the local address and port number. The following program is used to establish a connection with the previous server-side program and display the information sent by the server on the standard output.
/ * *
* function: this is a client program that is used to establish a connection with the previous server-side program and display the information sent from the server on the standard output
, /
Package com.xushouwei
/ / introduce the corresponding package
Import java.net.*
Import java.io.*
Public class TClint
{
Public static void main (String [] args)
{
/ / define the Socket class
Socket s1
/ / define the InputStream class
InputStream s1In
/ / define the DataInputStream class
DataInputStream dis
Try
{
/ / Open the connection on port 1314
S1=new Socket ("127.0.0.1" 1314)
/ / get the input handle of the socket port and read data from it
S1In=s1.getInputStream ()
Dis=new DataInputStream (s1In)
String st=new String (dis.readUTF ())
System.out.println (st)
/ / close the data flow and socket connection at the end of the operation
Dis.close ()
S1In.close ()
S1.close ()
} catch (Exception e)
{
E.printStackTrace ()
}
}
}
The above is how to use the Socket interface in Java. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
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.