1. Client / Server NetworkingJava With Socket to complete the communication of all its network underlying, Socket is a channel of communication, which can transmit and receive data through a specific end. Socket in Java can be divided into two categories: (1) Datagram sockets: Packets Socket; (2) Stream Sockets: Stream socket; 1.2 DataGram SocketDataGram Socket Using UDP to implement data communication, so it does not guarantee data to reach the destination, However, because it does not require a dedicated network link, it is relatively less required to have more resources. DataGram sends data in a package, but it does not guarantee that these packets arrive in a specific order, so the package often needs to include the sequence number, and the recipient can determine whether all packages have been received in accordance with the information of the serial number. And reorganize these packages in normal order. Java supports DataGram Socket through two class DataGramsocket and DataGrampacket. DataGramsocket implements the basic features of DataGram Socket, while DataGrampacket provides some support for packages. Several important methods for DataGramsocket: (1) DataGramsocket (): Randomly bind a valid port; (2) DataGramsocket: Bind the specified port; (3) Void Send (DataGrampacket P): Send Data News Since the address information of the destination is included in the datagram, it is not necessary to provide address information in this function; (4) Synchronized Void Rece (DataGrampacket P): Receive packets, thread security; (5) Synchronized void Close : Turn off the socket; do not distinguish serversocket and clientsocket in DataGramsocket, if you must distinguish, then send a client, and receive the server.
DataGrampacket has several important methods: (1) DataGrampacket (Byte Ibuf [], INT iLEngth: used to receive datagram; (2) DataGrampacket (Byte IBUF [], INT ILENGTH, INETDRESSIADDR, IPORT): Used for Sended datagram; (3) BYTE [] getData () (4) INT getLength () The following is an example of a complete DataGram Socket: Receiver, Server End Code: Import Java.io. *; Import Java.net. * ; class FortuneServer1 extends Thread {DatagramSocket ServerSocket; public FortuneServer1 () {super ( "FortuneServer1"); try {ServerSocket = new DatagramSocket (1114); System.out.println ( "FortuneServer up and running ...");} catch (SocketException e) {System.err.println ( "Exception: could not create datagram socket"); System.exit (1);}} public static void main (String [] args) {FortuneServer1 server = new FortuneServer1 () Server.Start ();} public void run () {if (serversocket == null) return; while {Try {inetaddress address; int port; DataGrampacket Packet; Byte [] data = new byte [256]; int Num = 1; packet = new data.length; serversocket.Receive (packet); address = packet.getaddress (); port = packet.getport () File infile = new file ("fortunes.txt"); fileinputstream instream = new fileinputstream (infile); if (Instream.Read (data) <= 0) {System.err.Println ("Error: COULDN '' '' er er) ");
} Packet = new data, address, port); serversocket.send (packet);} catch (Exception E) {system.err.println ("Exception:" E); E.PrintStackTrace () }}}} Description: (1) The Socket of the receiving end uses a multi-thread, and the concept of multi-threading can refer to the multi-thread portion of this article; (2) created a DataGramsocket in the constructor, and uses 1114 port (3) The key function of this example is RUN, which uses a dead loop, using the receive method in the loop to listen to the 1114 port, if the 1114 port does not request the data, then this program is staying in Receive, No longer executing; (4) When there is data on the 1114, the received DataGrampacket data package is placed in the Packet in the Packet, then parsing the data, get the address information of the sender; (5) and then Create a DataGrampacket package and populate the data to the original receiver.
The following is the code of the sender: import java.io. *; Import java.net. *; Class fortuneclient {public static void main (string args []) {FortuneClient client = new fortuneclient (); system.out.println (Client. getMessage ());} public String getMessage () {String fortune; try {DatagramSocket socket; DatagramPacket packet; byte [] data = new byte [256]; socket = new DatagramSocket (); packet = new DatagramPacket (data, data. Length, inetaddress.getbyName ("127.0.0.1"), 1114); socket.send (packet); packet = new data.length; socket.Receive (packet); Fortune = new string (Packet.getdata (), 0); socket.close ();} catch (unknownhostExcection e) {system.err.println ("Exception: host could not be found"; return null;} catch (exception e) {system.err. Println ("Exception:" E); E.PrintStackTrace (); return null;} Return Fortune;}} The client's code is basically the same as the server side, but there is no loop, and the processing step is the basically the basis of the server side. This also shows that DataGram Socket does not really distinguish Server and Client. 1.3 Stream SocketStream Socket Unlike DataGram Socket, it has a permanent link to ensure that data is reliable to each other. But the resources occupied by Stream Socket more. Java mainly implements Stream Socket through Socket and Serversocket, one for the client, another user server side.
Several important methods of the Socket class are as follows: (1) Socket (STRING HOST, INT Port) (2) Socket (Inetaddress Address, INT Port) (3) Synchronized Void Close () (4) InputStream GetInputStream () (5) OutputStream getOutputStream () can see the difference between Socket in the Socket in the Stream Socket: (1) In the constructor, you need to specify the address of the server and the port, which is used to create a link before sending the data, and DataGram's socket There is no need to establish a link, it only needs to include address information in the packet to be sent; (2) two important methods for stream sockets and other streams, and similar in operation, actually operational STREM SOCKET As long as the link is established, then the following operations and stream operations are the same, you can forget you in operation socket, just do your own ordinary stream. Serversocket has the following important methods: (1) ServerSocket (int port): listening to the specified port, the listening time is the default value 50; (2) Serversocket (int port, int count): Monitor the specified port and specify the listening time; (3) ServerSocket (INT port, INT BACKLOG, INETADDRESS BINDADDR): Only the data sent by the specified interface; (4) Socket Accept (): Accpet method returns a socket object, get the GetInputStream and getOutputStream method using the socket object Enter and output flow. This shows that whether the server side or the client, they are all through the socket object to send and receive data. When the program executes to the ACCPET, it will enter the listening state, and no longer perform the data until the data is received. (5) Void Close () The following is an example of stream socket, in which separate two class receiver and sender are responsible for operating the specified input and output stream, use another class socketperformer to create Receiver and Sender The instance of these two classes, incorporates the specified input and output stream, and in both classes of Client and Server, be responsible for creating a socketperformer object and passes to the specified socket. Therefore, these five classes are functions three floors, the first layer is responsible for the operation, and the second layer is responsible for creating the specified Socket stream, and these Socket streams to the first layer, the third layer is responsible for creating sockets and putting these Socket Transmit to the second layer.
Receriver Code: package socketChat; import java.io.BufferedReader; public class Receiver extends Thread {BufferedReader reader; public Receiver (BufferedReader theSocketReader) {reader = theSocketReader;} public void run () {while (true) {try {String words = Reader.readLine (); System.out.println ("/ R / N <<<" Words);} catch (Exception E) {E.PrintStackTrace (); return;}}}} sender code: package socketchat; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; public class Sender extends Thread {PrintWriter writer; public Sender (PrintWriter theWriter) {writer = theWriter;} public void run () {try { While (true) {bufferedreader consolereader = new bufferedreader (STRING UserInput = consolereader.read Line (); Writer.Write (userinput "/ r / n"); Writer.Flush (); // send the data in buffer immediately}} catch (exception e) {E.PrintStackTrace (); Return;}} } SocketPerformer Code: package socketChat; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class SocketPerformer {Socket socket; public SocketPerformer (Socket theSoc) {socket = THROWS Exception {Bufferedreader SocketReader = New BufferedReader (socket.getInputStream ()));
PrintWriter socketWriter = new PrintWriter (socket.getOutputStream ()); System.out.println ( "connection built!"); Receiver rec = new Receiver (socketReader); rec.start (); Sender sender = new Sender (socketWriter); sender.start ();}} Server Code: package socketChat; import java.net.ServerSocket; import java.net.Socket; public class Server {public static void main (String [] args) throws Exception {ServerSocket server = new ServerSocket (30000, 5); socket socket = null; system.out.println ("waiting incoming connection ..."); socket = server.accept (); system.out.println ("a connection built!"); System .out.println ("The Peer IP IS:" Socket.getinetaddress (). getHostaddress (); new socketperformer (Socket) .execut (); server.close ();}}}} The client code is as follows: package socketchat; Import java.net.socket; public class client {public static void main (string [] args) throws exception {string i P = "127.0.0.1"; int port = 30000; System.out.Println ("Connecting to Server:" IP "At Port: Port " ... "); Socket SoC = New Socket (IP , New SocketPerformer (SOC) .execut ();}} 2. Other (1) constant definitions are modifiers in Final, such as Final Int i = 3; Final can also be used on Class and Method, if used On the Class, then the Class cannot be inherited. If used on the Method, then the Method cannot be overloaded (2) Class variable definition: Static int SUM (3) Judgment Object Type: ObjName InstanceOf ClassName, such as "HelloWorld" instanceof string ,