Using Java to implement DBP communication process Wayne
Database (DATAGRAM) makes a logical packet format of information on the media on the media.
It is a message propagating, independent, own, which contains address information, can it reach the destination,
The time arrived, whether the content will change when the content is reached, can not be accurately known. Its communication parties do not need to establish
Connected, for some applications that do not require high quality, Datashers Newsletter is a very good choice.
There are two types of DataGramsocket and DataGramSocket and DataGrampacket in Java's Java.net package.
Network communication is reported to communicate.
Below, I want to explain in detail in Java to implement the data newsletter of the client and the server, please see
:
First, the workflow of the client application
1) First, I want to establish a socket, we can create a DataGramsocket object.
To achieve it, there are two ways of constructing in the DataGramsocket class in Java:
a) Public DataGramsocket () Constructs a datagram, and makes it available with the local host
Port connection. If you can't open the socket, you will throw the socketException exception.
b) Public DataGramsocket (int port) Constructs a datagram socket and specifies it with the local host
Port connection. If you can't open a socket or socket, you cannot connect the socketException as the specified port.
often.
2) Create a data packet to implement unconnected package delivery services. Each data packet is used
DataGrampacket class to create, DataGrampacket object encapsulate data package data, package length, target ground
Address, target port. As a client to send a data packet, you want to call the DataGrampacket class as follows
The constructor creates a DataGrampacket object, and puts the data to be sent into the object.
.
DataGrampacket (byte bufferedarray [], int length, INT port)
A package length is transmitted to the packet of the specified host specified port number, the parameter Length must
Less than or equal to BUFFEREDARRY.LENGTH
The DataGrampacket class provides four classes to get information
a) Public Byte [] getData () Returns a byte array, contains data in the datagret to send.
b) Public int getLength () returns the length of the transmitted or received data
c) Public inetaddress getaddress () Returns an IP place that sends or receives this data.
site
d) PUBLIC INT getPort () Returns the port number of the remote host that sends or receives the datagram.
3) Create a DataGramsocket and a DataGrampacket object, you can send a data packet package. hair
Send is implemented by calling the Send method of the DataGramsocket object, it needs to be a DataGrampacket object
Number, the data that has just been encapsulated into the DataGrampacket object is reported.
4) Of course, we can also receive data packets, in order to receive result data packets returned from the server.
We need to create a new DataGrampacket object, which requires another kind of DataGrampacket
Constructed DataGrampacket (Byte BufferedArray [], INT Length, ie the buffers and lengths of the received datagram are required. Call the Receive () method of the DataGramsocket object to complete the work received
For this, the DataGrampacket object you created above is required as a parameter. This method will blindly know
A data packet, at this time, the DataGrampacket buffer is included in the received data, data packets.
The package also includes information such as the sender's IP address, port number on the sender machine.
5) Handle data within the receiving buffer and obtain the results of the service.
6) When the communication is complete, you can use the close () method of the DataGramsocket object to close the duo communication.
Socket. Of course, Java will automatically close the socket, release the DataGramsocket and DataGrampacket.
Use resources. But as a good program habit, it is also to be displayed. Below I give a simple client program that utilizes the datagram, it can complete the simple connection with the server.
News. For intuitive, I wrote it into an applet program. Since this article is not introducing Applet, I only write simple
To the comment, friends who are interested in applet relatives about books.
Import java.applet. *; import java.aw. *; import java.net. *; import java.io. *;
public final class javaCommunicationClient extends Applet {private Label label1, label2; private Panel panel1, panel2; private TextField textfield; private TextArea textarea; private DatagramSocket sendSocket, receiveSocket; // declare transmitting and receiving data packets Socket
Data News Socket Private Datagrampacket SendPacket, ReceivePacket; // Declaration Send Data Packet Package and Receive
According to the packet
Public void init () {setBackground (color.gray); setLayout (new borderLayout ()); // Set a layout manager panel1 = new panel (); panel1.setLayout (new borderLayout ()); // In the container Place layout manager label1 = new label ("call record"); textarea = new textarea (10, 20); // Text display area TextArea.Settext ("Welcome!"); Panel1.add ("North", label1 ); // Add the label to the layout manager Panel1.add ("center", textarea); add ("north", panel1); label2 = new label ("Speech:"); // Create another container Panel2 .add ("center", label2); TextField = New TextField (20); TextField.Settext (""); Panel2.add ("South", TextField; add ("center", panel2); show (); } public void start () {waitforpacket ();
Public void waitforpackets ()
/ * Method WaitforPacket is used to listen to the server's datagram, after the data is obtained, in the text
Zone is displayed
* / {Try {sendSocket = new datagramsocket (); // instantiate a send datagram SOCKET object received (5001); / / instantiate a receive dataginary SOCKET object
Port with 5001 as a port
} catch (socketexception e) // captures exception {textarea.AppendText ("You cannot open Date Socket, or Datasher Socket Unable to specify port
Connection! ");} While (true) {type {byte buf [] = new byte [100]; receivepacket = new data; // instantiate a receive data
Packet object
ReceiveSocket.Receive (ReceivePacket); // accepts textArea.AppendText ("/ n server: / t") with receivepacket; Byte [] data = receivepacket.getdata (); string receivedstring = new string (data) TextArea.AppendText (ReceiveDString); // // Show the data in the received data packet newspaper
Come out} catch (ioException e) {textarea.appendtext ("Network communication error, problem in" E.TOString ());}}}
Public Boolean Action (EVENT E, Object O) {Try {textarea.AppendText ("/ n client:"); string string = o.to.tostring (); textarea.appendtext (string); byte [] DATABYTE = New Byte [ 100]; String.getbytes (0, String.Length (), Databasete, 0); SendPacket = NewDataGrampacket (DatabaseTe, String.length (), inetaddress.getbyname ("202.38.64.4"), 5000); //
Send a datagram, where you can use the IP address SendSocket.send (IOException IoE) {textarea.AppendText in your own host IP replacement;} catch ("iException IoE) {textarea.AppendText (" Network Communication error, problem in " IoE.Tostring ());} Return True;
}
Second, the workflow of the server-side application
Unlike data stream communication, do not establish a connection between communication between the communication communication, communication,
Therefore, the server application communication process and the client application communication process make very similar, but also
DITAGRAGRAMSOCKET, build data packets DataGrampacket, receive data report and number of transmission
It is reported that the data in the receiving buffer is reported. After the communication is completed, the Data News is turned off. the difference is,
The server application is to face all the computers in the network, so the server application receives a package of text.
Analyze it, get the source address information of the datagram, so that the correct return result packet can be created to the client.
Below I gave a server segment program for a datagram, due to the corresponding application of the server and
The client program is similar, so I don't want a detailed note, only list the program for your reference:
1, JavacommunicationsServer.java
Import java.net. *; import java.io. *; import java.awt. *; import java.applet.applet;
public final class javaCommunicationServer extends Frame {private Label label1, label2; private Panel panel1, panel2; private TextField textfield; private String name, name1; private TextArea textarea; private DatagramSocket sendSocket, receiveSocket; private DatagramPacket sendPacket, receivePacket;
Public JavachatServer () {Super ("Communication Console:"); // Use a superclass construction method to construct a frame panel1 = new panel (); Panel1.setLayout (new borderLayout ()); label1 = new label ("call Record "); Textarea = New Textarea (10, 20); TextArea.Settext (" Welcome! "); Panel1.Add (" North ", Label1); Panel1.Add (" Center ", Textarea); add (" North ", Panel1); Panel2 = new panel (); Panel2.setLayout (New borderLayout ()); label2 = new label (" Speech: "); Panel2.add (" center ", label2); TextField = New TextField 20); Panel2.add ("South", TextField; add ("center", panel2); show ();
Try {sendsocket = new databaseocket = new databaseocket (5000);} catch (socketexception e) {E.PrintStackTrace (); system.exit (1);}}
public void waitForPacket () {while (true) {try {byte buf [] = new byte [100]; receivePacket = new DatagramPacket (buf, buf.length); receiveSocket.receive (receivePacket); name = receivePacket.getAddress () .tostring (); if (Name1! = Name) {textarea.appendtext ("/ N from host:" name "/ n port:
" received ();} textarea.appendtext (" / n client: / t "); byte [] data = receivepacket.getdata (); string receivedstring = new string (data, 0); Textarea.AppendText ( ReceivedString; Name1 = Name;}
Catch (ioException e) {textarea.appendtext ("Network communication error, problem in" E.TOSTRING ());}}}
Public Boolean Handleevent (EVENT E) {if (E.ID == Event.windows_Destroy) {hide (); dispose (); system.exit (0);} Return Super.Handleevent (E);} public boolean action E, Object O) {Try {textarea.AppendText ("/ n server:"); string string = o.to.tostring (); textarea.appendtext (string); byte [] dataByte = new byte [100]; string.getbytes (0, String.Length (), Databyte, 0); sendpacket = new
DataGrampacket (DataByte, String.Length (), inetaddress.getbyname (name), 5001); SendSocket.send (SendPacket);} catch (ioException ie) {textarea.appendtext ("Network communication error, problem is" IOE. Tostring ());} Return True;
}
2, CommunicationServerRun.java, establish an instance of JavacommunicationServer, then run
.
import javaCommunicationServer class CommunicationServerRun extends javaCommunicationServer {public static void main (String args []) {javaCommunicationServer cs = new javaCommunicationServer (); cs.waitForPacket ();}}