Java entry note 9

xiaoxiao2021-03-06  46

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;

Public class sender extends thread {

PrintWriter Writer;

PUBLIC Sender (PrintWriter theWriter) {Writer = thewriter;

}

Public void run () {

Try {

While (true) {

BufferedReader consolereader = New BufferedReader

New INPUTSTREAMREADER (System.IN));

String UserInput = consolereader.readline ();

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 theseoc) {

Socket = theseoc;

}

Public void execut () throws exception {

BufferedReader socketreader = New BufferedReader (New InputStreamReader (NEW

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 storage!");

System.out.println ("The Peer IP IS:" Socket.Getinetaddress (). Gethostaddress ());

New socketperformer (socket) .execut ();

Server.close ();

}

The client end code is as follows:

Package socketchat;

Import java.net.socket;

Public class client {public static void main (string [] args) throws exception {

String IP = "127.0.0.1";

INT port = 30000;

System.out.println ("Connecting to Server:" IP

"at port:" port "...");

Socket SoC = New Socket (IP, Port);

New socketperformer (SOC) .execut ();

}

2. Others

(1) Constant definitions are modified 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 Method, then this Method Can't be overloaded

(2) Class variable definition: static int sum

(3) Judgment Object Type: ObjName InstanceOf ClassName, such as "HelloWorld" instanceof string, the result of judgment is TRUE

(4) Extract the class name: objName.getClass (). Getname ()

(5) Java.lang: Java's most basic package, including the most basic definition of Java language

(6) java.util: Contains such as Date, and basic collection, such as Vector, HashTable, etc.

(7) java.io: Contains the definition of the input and output

(8) java.net: Contains such as Socket, etc.

(9) java.awt: Used for Window interface development

(10) java.applet: Used for Applet development

(11) NULL keyword reference null object, pay attention to case

(12) Each basic data type, such as int, has corresponding classes and corresponding INT

(13) The constructor name is the same as the class name, and does not need to return the type, that is, it does not need to add type modifier before constructor.

(14) Call the constructor: this (parameter list);

(15) Call the constructor of the parent class: Super (a list);

(16) Call the function of the parent class has been overloaded: super. Method name (parameter list);

(17) There may be multiple definitions in the same file, but only one class is public and class names are the same as the file. After the file is successfully compiled, it will generate multiple .class files, definition with the class ;

(18) The interface is stronger than the abstract class: abstract class belongs to a specific class structure tree, which cannot be shared by class in other trees;

(19) The definition of the interface is similar to the definition of the class. Simply change the Class to Interface, but the interface definition must be public or default (package); (20) can define methods and variables in the interface, in the interface The definition method should be public and is Abstract (default); the definition of variables must be public static final (default);

(21) String.copyValueof (Buffer, 0, Offset): Used to remove characters from the character array and form a string;

(22) New String (buf, 0, count)

(23) System.in is an InputStream;

(24) System.err is a PrintStream;

(25) System.out is a PrintStream;

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

New Post(0)