Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the low-level Java Network programming of Socket

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how to understand the low-level Java network programming of Socket. The content of the article is of high quality, so the editor will share it with you for reference. I hope you will have some understanding of the relevant knowledge after reading this article.

Low-level Java Network programming of Socket

1 Socket communication

Two programs on the network exchange data through a two-way communication connection, and one end of this two-way link is called a Socket. Socket is usually used to achieve the connection between the client and the server. Socket is a very popular programming interface of the TCP/IP protocol, and a Socket is uniquely determined by an IP address and a port number.

In Java environment, Socket programming mainly refers to network programming based on TCP/IP protocol.

2 the general process of Socket communication

The general connection process of Client/Server programming with Socket is as follows: the server side Listen (listens) whether there is a connection request on a port, the client side sends a Connect (connection) request to the Server side, and the server sends back an Accept (accept) message to the Client side. 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 create Socket

Java provides two classes, Socket and ServerSocket, in the package java.net to represent the client and server of a two-way connection, respectively. These are two very well encapsulated classes that are easy to use. The construction method is as follows:

Socket (InetAddress address, int port)

Socket (InetAddress address, int port, boolean stream)

Socket (String host, int prot)

Socket (String host, int prot, boolean stream)

Socket (SocketImpl impl)

Socket (String host, int port, InetAddress localAddr, int localPort)

Socket (InetAddress address, int port, InetAddress localAddr, int localPort)

ServerSocket (int port)

ServerSocket (int port, int backlog)

ServerSocket (int port, int backlog, InetAddress bindAddr)

Where address, host and port are the IP address, host name and port number of the other party in the two-way connection, stream indicates whether socket is a stream socket or Datagram socket,localPort represents the port number of the local host, localAddr and bindAddr are the addresses of the local machine (the host address of ServerSocket), and impl is the parent class of socket, which can be used to create both serverSocket and Socket. Count represents the maximum number of connections that the server can support. For example:

Socket client = new Socket ("127.0.0.1", 80)

ServerSocket server = new ServerSocket (80)

Note that care must be taken when selecting ports. Each port provides a specific service, and only when the correct port is given can the corresponding service be obtained. The port number of 0Secret1023 is reserved by the system, for example, the port number of http service is 80jiao telnet service, and the port number of 21Graver ftp service is 23, so when we choose a port number, it is best to choose a number greater than 1023 to prevent conflicts.

If an error occurs when creating a socket, an IOException will be generated and must be dealt with in the program. So an exception must be caught or thrown before creating a Socket or ServerSocket.

4 simple Client/Server programming

The following is a demo of a typical client-server interaction with Socket, which will have a deeper understanding of the concepts discussed above. Please refer to the notes for the meaning of the program.

1. Client program

Import java.io.*

Import java.net.*

Public class TalkClient {

Public static void main (String args []) {

Try {

Socket socket=new Socket ("127.0.0.1" 4700)

/ / send a customer request to port 4700 of this machine

BufferedReader sin=new BufferedReader (new InputStreamReader (System.in))

/ / construct BufferedReader objects from system standard input devices

PrintWriter os=new PrintWriter (socket.getOutputStream ())

/ / get the output stream from the Socket object and construct the PrintWriter object

BufferedReader is=new BufferedReader (new InputStreamReader (socket.getInputStream ()

/ / get the input stream from the Socket object, and construct the corresponding BufferedReader object

String readline

Readline=sin.readLine (); / / read a string from the system standard input

While (! readline.equals ("bye")) {

/ / stop the loop if the string read from standard input is "bye"

Os.println (readline)

/ / output strings read from system standard input to Server

Os.flush ()

/ / refresh the output stream so that Server receives the string immediately

System.out.println ("Client:" + readline)

/ / print the read string on the system standard output

System.out.println ("Server:" + is.readLine ())

/ / read a string from Server and print it to standard output

Readline=sin.readLine (); / / read a string from the system standard input

} / / continue the cycle

Os.close (); / / close the Socket output stream

Is.close (); / / close the Socket input stream

Socket.close (); / / close Socket

} catch (Exception e) {

System.out.println ("Error" + e); / / if there is an error, the error message is printed.

}

}

}

two。 Server-side program

Import java.io.*

Import java.net.*

Import java.applet.Applet

Public class TalkServer {

Public static void main (String args []) {

Try {

ServerSocket server=null

Try {

Server=new ServerSocket (4700)

/ / create a ServerSocket to listen for customer requests on port 4700

} catch (Exception e) {

System.out.println ("can not listen to:" + e)

/ / error, print error message

}

Socket socket=null

Try {

Socket=server.accept ()

/ / use accept () blocking to wait for customer request. There are customers.

/ / when the request arrives, a Socket object is generated and execution continues.

} catch (Exception e) {

System.out.println ("Error." + e)

/ / error, print error message

}

String line

BufferedReader is=new BufferedReader (new InputStreamReader (socket.getInputStream ()

/ / get the input stream from the Socket object, and construct the corresponding BufferedReader object

PrintWriter os=newPrintWriter (socket.getOutputStream ())

/ / get the output stream from the Socket object and construct the PrintWriter object

BufferedReader sin=new BufferedReader (new InputStreamReader (System.in))

/ / construct BufferedReader objects from system standard input devices

System.out.println ("Client:" + is.readLine ())

/ / print the string read from the client on the standard output

Line=sin.readLine ()

/ / read a string from standard input

While (! line.equals ("bye")) {

/ / if the string is "bye", stop the loop

Os.println (line)

/ / output the string to the client

Os.flush ()

/ / refresh the output stream so that Client receives the string immediately

System.out.println ("Server:" + line)

/ / print the read string on the system standard output

System.out.println ("Client:" + is.readLine ())

/ / read a string from Client and print it to standard output

Line=sin.readLine ()

/ / read a string from the system standard input

} / / continue the cycle

Os.close (); / / close the Socket output stream

Is.close (); / / close the Socket input stream

Socket.close (); / / close Socket

Server.close (); / / close ServerSocket

} catch (Exception e) {

System.out.println ("Error:" + e)

/ / error, print error message

}

}

}

On how to understand Socket low-level Java network programming to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report