CLIENT / Server Networking
Java completes its communication through socket, and 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 Socket
DataGram Socket uses UDP to implement data communication, so it does not guarantee that data can reach the destination, but because it does not require a dedicated network link, it is relatively less required.
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 binds an effective port;
(2) DataGramsocket: Binds the specified port;
(3) Void Send (DataGrampacket P): Send Datashers, Since the address information of the destination is included in the datagram, no address information is provided in this function;
(4) SYNCHRONIZED VOID Receive (DataGrampacket P): Receive packets, thread security;
(5) Synchronized void close (): Turn off the socket;
Don't distinguish serverSocket and ClientSocket in DataGramsocket, if you must distinguish, the send is a Client, and the received is Server.
DataGrampacket has several important methods:
(1) DATAGRAMPACKET (Byte Ibuf [], INT ILENGTH): Used to receive datagram;
(2) DataGrampacket (Byte Ibuf [], INT ILENGTH, INETADDRESSIADDR, INT IPORT: Denual Data for Send;
(3) Byte [] getData ()
(4) INT getLength ()
The following is an example of a complete DataGram Socket:
Receive terminal, 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: Couldn't 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 (True)
{
Try
{
Inetaddress address;
Int port;
DataGrampacket packet;
Byte [] Data = New Byte [256];
INT NUM = 1;
Packet = New DataGrampacket (Data, 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't ReaduN);
}
Packet = New DataGrampacket (Data, Data.Length, Address, Port)
Serversocket.send (packet);
}
Catch (Exception E)
{
System.err.Println ("Exception:" E);
E.PrintStackTrace ();
}}}}
Description:
(1) The SOCKET in this example uses a multi-thread, and the concept of multi-thread can refer to the multi-threaded portion of this article;
(2) Create 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 has stayed in Receive, not Re-execution;
(4) When the data is 1114, the received DataGrampacket data package is placed in the Packet in the Packet, and then parsing the data in which the sender's address information is obtained;
(5) 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 DataGrampacket (Data, Data.Length);
Socket.Receive (Packet);
Fortune = new string (packet.getdata (), 0);
Socket.close ();
}
Catch (UnknownHOSTEXCEE) {
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 code of the server side, but there is no loop, and the processing step is the substantially opposite of the server side. This also shows that DataGram Socket does not really distinguish Server and Client.
1.3 Stream Socket
Stream Socket is different from DataGram Socket, which 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 for 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 ()
It can be seen that the difference between Socket in Stream Socket and the Socket in DataGram Socket:
(1) In the constructor, here you need to specify the address and port of the server, which is used to establish a link before it sends data, and DataGram's socket does not need to establish a link, it only needs to contain address information in the packet to send. ;
(2) The two important methods of stream socket are similar, and similar to other streams, it is similar, in fact, when the Stream Socket is operated, as long as the link is established, then the subsequent operation and flow operation are the same, you can forget You are working on Socket, just do your own normal stream. Serversocket has the following important methods:
(1) Serversocket: listen 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 an Socket object to get the input and output stream using the GetInputStream and GetputStream methods of the Socket object. 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 streams, use another class socketperformer to create two classes of Receiver and Sender, And pass the specified input and output stream, and in both classes of Client and Server, you are responsible for creating a SocketPerformer object and passed into 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 THSocketReader) {
Reader = THHESOCKETREADER;
}
Public void run () {
While (true) {
Try {
String word = 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;