Java Review of network communication

Source: Internet
Author: User
Tags new set

In this article, we mainly discuss how to use Java for network communication, including TCP communication, UDP communication, multicasting, and NiO.

TCP connections

TCP is based on the socket, in the TCP connection, we will use ServerSocket and sockets, when the client and the server to establish a connection, the rest of the basic is the I/O control.

Let's take a look at a simple TCP communication, which is divided between the client and the server side.

The client code is as follows:

Simple TCP Client Import java.net.*;import java.io.*;p ublic class Simpletcpclient {public static void main (string[] args) throw        s IOException {socket socket = NULL;        BufferedReader br = null;        PrintWriter pw = null;        BufferedReader brtemp = null;            try {socket = new socket (Inetaddress.getlocalhost (), 5678);            br = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));            PW = new PrintWriter (Socket.getoutputstream ());            Brtemp = new BufferedReader (new InputStreamReader (system.in));                while (true) {String line = Brtemp.readline ();                Pw.println (line);                Pw.flush ();                if (Line.equals ("End")) break;            System.out.println (Br.readline ());        }} catch (Exception ex) {System.err.println (Ex.getmessage ());  } finally {if (socket! = NULL) socket.close ();          if (br! = null) br.close ();            if (brtemp! = null) brtemp.close ();        if (PW = null) pw.close (); }    }}

  

The server-side code is as follows:

Simple version TCP server-side import java.net.*;import java.io.*;p ublic class Simpletcpserver {public static void main (string[] args) thr        OWS IOException {ServerSocket server = null;        Socket client = null;        BufferedReader br = null;        PrintWriter pw = null;            try {server = new ServerSocket (5678);            Client = Server.accept ();            br = new BufferedReader (New InputStreamReader (Client.getinputstream ()));            PW = new PrintWriter (Client.getoutputstream ());                while (true) {String line = Br.readline ();                Pw.println ("Response:" + line);                Pw.flush ();            if (Line.equals ("End")) break;        }} catch (Exception ex) {System.err.println (Ex.getmessage ());            } finally {if (server! = null) server.close ();            if (client! = NULL) client.close ();            if (br! = null) br.close (); If(PW = null) pw.close (); }    }}

  

The function of the server here is very simple, it receives the message from the client, and then returns the message "intact" to the client. When the client sends "end", the communication ends.

The above code basically outlines the TCP communication process, the client and the server side of the main framework, we can find that the above code, the server side at any moment, can only handle a request from the client, it is serial processing, not parallel, and we are not impressed with the server processing method is not the same, We can add multiple threads to the server, and when a client's request comes in, we create a thread to process the corresponding request.

The improved server-side code is as follows:

 1 Import java.net.*; 2 Import java.io.*; 3 public class Smarttcpserver {4 public static void main (string[] args) throws IOException 5 {6 Serverso Cket Server = new ServerSocket (5678); 7 while (true) 8 {9 Socket client = server.accept (); thread thread = new Servert Hread (client), Thread.Start (),}13}14}15 class Serverthread extends Thread17 {priv     ATE socket socket = null;19 public serverthread (socket socket) {This.socket = socket;23}24         public void Run () {BufferedReader br = null;27 printwriter pw = null;28 try29 {br = new BufferedReader (New InputStreamReader (Socket.getinputstream ())), PW = new Printwrite                 R (Socket.getoutputstream ()); + (True) @ {String line = Br.readline (); 35 Pw.println ("Response:" + line);. Flush (); PNs if (Line.equals ("End")) break;38}39}40 catch (Exception ex) 41 {System.err.println (Ex.getmessage ());}44 finally45 {sock                     ET = null)-try {socket.close (); IOException catch (E1) {50                     E1.printstacktrace ();}52 if (br! = null) try {54                 Br.close (); the catch (IOException e) {e.printstacktrace (); 57 }58 if (pw = null) Pw.close (); 59}60}61}

On the modified server side, multiple requests from the client can be processed at the same time.

In the process of programming, we will have the concept of "resources", for example, database connection is a typical resource, in order to improve performance, we usually do not directly destroy the database connection, but use the database connection pool way to manage multiple database connections, has been implemented for reuse purposes. It is also a resource for a socket connection, and when our program requires a large number of socket connections, it would be very inefficient if each connection needs to be re-established.

Similar to the database connection pool, we can also design a TCP connection pool, the idea is that we use an array to maintain multiple sockets, another State array to describe whether each socket connection is in use, when the program needs a socket connection, we traverse the state array, Remove the first unused socket connection and throw an exception if all connections are in use. This is a very straightforward "scheduling strategy", in many open-source or commercial framework (APACHE/TOMCAT), there will be similar "resource pool."

The code for the TCP connection pool is as follows:

Multithreaded version of TCP server-side import java.net.*;import java.io.*;p ublic class Smarttcpserver {public static void main (string[] args) th        Rows IOException {serversocket server = new ServerSocket (5678);            while (true) {Socket client = server.accept ();            Thread thread = new Serverthread (client);        Thread.Start ();    }}}class Serverthread extends thread{private socket socket = NULL;    Public serverthread (socket socket) {this.socket = socket;        public void Run () {BufferedReader br = null;        PrintWriter pw = null;            try {br = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));            PW = new PrintWriter (Socket.getoutputstream ());                while (true) {String line = Br.readline ();                Pw.println ("Response:" + line);                Pw.flush ();            if (Line.equals ("End")) break; }} catch (ExcePtion ex) {System.err.println (Ex.getmessage ());                } finally {if (socket! = null) try {socket.close ();                } catch (IOException E1) {e1.printstacktrace ();                } if (br = null) try {br.close ();                } catch (IOException e) {e.printstacktrace ();        } if (pw = null) pw.close (); }    }}

  

UDP connection

UDP is a different connection with TCP, it is often used in the real-time requirements are high, alignment determination requirements are not high, such as online video. UDP will have a "packet loss" situation occurs, in TCP, if the server does not start, the client sends a message, the exception will be reported, but for UDP, no exception is generated.

UDP communication uses two classes when Datagramsocket and Datagrampacket, which store the content of the communication.

Here is a simple example of UDP communication, like TCP, also divided into the client and server two parts, the client terminal code is as follows:

A simple TCP connection pool import java.net.*;import java.io.*;p ublic class Tcpconnectionpool {private inetaddress address = null;    private int port;    Private socket[] arrsockets = null;    Private boolean[] Arrstatus = null;        private int count;        Public Tcpconnectionpool (inetaddress address, int port, int count) {this.address = address;        This.port = port;        this. Count = Count;        Arrsockets = new Socket[count];                Arrstatus = new Boolean[count];    Init ();                } private void Init () {try {for (int i = 0; i < count; i++) {                Arrsockets[i] = new Socket (address.gethostaddress (), port);            Arrstatus[i] = false;        }} catch (Exception ex) {System.err.println (Ex.getmessage ());        }} public Socket getconnection () {if (arrsockets = = null) init ();        int i = 0;     for (i = 0; i < count; i++) {       if (arrstatus[i] = = False) {Arrstatus[i] = true;            Break                }} if (i = = count) throw new RuntimeException ("has no connection availiable for now.");    return arrsockets[i];        } public void Releaseconnection (socket socket) {if (arrsockets = = null) init (); for (int i = 0; i < count; i++) {if (arrsockets[i] = = socket) {arrstatus[                I] = false;            Break    }}} public void ReBuild () {init ();                public void Destory () {if (arrsockets = = null) return;            for (int i = 0; i < count; i++) {try {arrsockets[i].close ();                } catch (Exception ex) {System.err.println (Ex.getmessage ());            Continue }        }    }}

  

The server-side code is as follows:

UDP Communication Client Import Java.net.*;import java.io.*;p ublic class UdpClient {public    static void Main (string[] args)    {        Try        {            InetAddress host = Inetaddress.getlocalhost ();            int port = 5678;            BufferedReader br = new BufferedReader (new InputStreamReader (system.in));            while (true)            {                String line = Br.readline ();                byte[] message = Line.getbytes ();                Datagrampacket packet = new Datagrampacket (message, Message.length, host, port);                Datagramsocket socket = new Datagramsocket ();                Socket.send (packet);                Socket.close ();                if (Line.equals ("End")) break;            }            Br.close ();        }        catch (Exception ex)        {            System.err.println (ex.getmessage ());        }    }}

  

Here, we also assume that, like TCP, when the client issues an "end" message, the communication ends, but in fact such a design is not necessary, the client side can be disconnected at any time, do not need to care about server side state.

Multicast (multicast)

Multicast in a similar way to UDP, it will use the Class D IP address and the standard UDP port number, Class D IP address refers to the address between 224.0.0.0 to 239.255.255.255, excluding 224.0.0.0.

The class used by multicast is MulticastSocket, which has two methods to focus on: Joingroup and Leavegroup.

Here is an example of a multicast, with the client code as follows:

UDP Communication Server-side import java.net.*;import java.io.*;p ublic class Udpserver {public    static void Main (string[] args)    { C2/>try        {            int port = 5678;            Datagramsocket dssocket = new Datagramsocket (port);            byte[] buffer = new byte[1024];            Datagrampacket packet = new Datagrampacket (buffer, buffer.length);            while (true)            {                dssocket.receive (packet);                String message = new string (buffer, 0, packet.getlength ());                System.out.println (Packet.getaddress (). GetHostName () + ":" + message);                if (Message.equals ("End")) break;                Packet.setlength (buffer.length);            }            Dssocket.close ();        }        catch (Exception ex)        {            System.err.println (ex.getmessage ());        }    }}

  

The server-side code is as follows:

Multicast Communication Client Import Java.net.*;import java.io.*;p ublic class Multicastclient {public    static void Main (string[] args)    {        BufferedReader br = new BufferedReader (new InputStreamReader (system.in));        Try        {            inetaddress address = inetaddress.getbyname ("230.0.0.1");            int port = 5678;            while (true)            {                String line = Br.readline ();                byte[] message = Line.getbytes ();                Datagrampacket packet = new Datagrampacket (message, message.length, address, port);                MulticastSocket multicastsocket = new MulticastSocket ();                Multicastsocket.send (packet);                if (Line.equals ("End")) break;            }            Br.close ();        }        catch (Exception ex)        {            System.err.println (ex.getmessage ());        }    }}

  

NIO (New IO)

NiO is a new set of IO APIs introduced by JDK1.4, which has a new design in buffer management, network communication, file access, and character set operations. For network communication, NIO uses the concept of buffers and channels.

Here is an example of NIO, which is very different from the code style we mentioned above.

Multicast communication server-side import java.net.*;import java.io.*;p ublic class Multicastserver {public static void main (string[] args) {        int port = 5678;            try {multicastsocket multicastsocket = new MulticastSocket (port);            InetAddress address = Inetaddress.getbyname ("230.0.0.1");            Multicastsocket.joingroup (address);            byte[] buffer = new byte[1024];            Datagrampacket packet = new Datagrampacket (buffer, buffer.length);                while (true) {multicastsocket.receive (packet);                String message = new string (buffer, packet.getlength ());                System.out.println (Packet.getaddress (). GetHostName () + ":" + message);                if (Message.equals ("End")) break;            Packet.setlength (buffer.length);        } multicastsocket.close ();        } catch (Exception ex) {System.err.println (Ex.getmessage ()); }    }}

  

The code above will attempt to access a local URL and then print out its contents.

Java Review of network communication

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.