Establish bidirectional communication with java.net package

zhaozj2021-02-17  37

Use the network capabilities provided by the Java.net package. Take a connection flow communication method,

The operation of the server is general:

(1) Create a ServerSocket object, in the specified port listening to the request.

(2) The accept () method will return a socket object when the request is received.

(3) Create an input and output stream object with the Socket object described above.

⑷ Interact with customers through input, output stream.

⑸ Intersection, turn off the input, output flow and socket.

⑹ The service program is running, and the ServerSocket is turned off.

Implement code code class such as:

Try {

Boolean flag = true; socket clientsocket = null;

Serversocket Serversocket = New Serversocket (0); System.out.Println ("Server Listen on:" ServerSocket.getlocalPort ());

while (flag) {clientSocket = serverSocket.accept (); DataInputStream is = new DataInputStream (new bufferedInputStream (client Socket.getInputStream ())); PrintStream os = new PrintStream (new bufferedOutputStream (clientSocket getOutputStream ()).); // Handling applet request os.close (); is.close (); clientsocket.close ();} serverSocket.close ();} catch (ooException e) {system.err.println ("Exception: e);}

The operation is:

(1) Creating a Socket object establishes a connection to the server.

(2) Enter, output flow with this Socket object.

(3) interacting with the server.

⑷ Intersection, turn off the input, output flow and socket.

Implement code classes such as:

try {Socket clientSocket = new Socket ( "serverName", 7); OutputStream os = clientSocket.getOutputStream (); DataInputStream is = new DataInputStream (clientSocket.getInputStream ()); // other operations os.close ();. is. Close (); clientsocket.close ();} catch (exception e) {system.err.println ("exception:" e);}

This approach relies only to standard Java network support, which does not require additional packages or tools, so it seems quite simple and flexible, easy to achieve certain special needs.

转载请注明原文地址:https://www.9cbs.com/read-30947.html

New Post(0)