Getting started from Java has been a year of scenery. Now talk about a year. First, Java foundation must be learned, you must master Java grammar rules. Next
It is the Grahpics and Swing package under AWT, the application programming must learn, and the IO is also extremely important, and then the network programming is reached.
Socket programming, start school Java with Socket programming to write "Four Wars" (because I am interested in the World War of the Lianzhong), write this game.
I am a month, every day is class programming, get out of class programming, busy every night to 12 o'clock, even dream is also programming, after a month, complete, the four countries can also normal
Opening, I am happy, this is the fun of programming. However, the first two months of Java (Java is the first door I learned and the programming language of the object), write it out
The things are chaotic, and the code written by Notepad, I don't know where I am adding, so I decided to revise it, this time I choose
JCREATOR, this is a good Java programming tool, find a method is not so hard, save me a lot of time, build a framework of the whole game system, I am ready to open
The beginning "Hand" is functional, so the first step encountered its own design application-level agreement, this is a headache problem, the command design makes the head, but also to consider the net
In addition to firewall, I will fight for a long time through firewall, I will have a long time, because there is still work (JSP development enterprise application).
The ingredients, I saw RMI, with a curiosity, I have seen it, then I have such a feeling, this East can not help me realize the network dialogue, not from
Write an agreement? Sure enough, it can do it! I feel that Java is too powerful, using RMI write network applications, do not have to design the protocol, do not need to consider data security yourself,
You don't have to consider the network firewall. My blood is boiling. After reading the RMI foundation in two days, I tested Hello, WORLD, I fought RMI to continue my game system "revolution".
Here, I don't have to introduce my game system in detail, because I haven't had time to fully implement its function. Here I want to pass a simple network application (chat
The sky room is to introduce RMI to all of the RMI.
The first step, let's take a look at what the chat room can do. Our chat room is ready to achieve the simplest function, everyone chats together. So the client needs a display
The text field of chat content, a text box that sends a message, and a send button. To support HTML syntax messages, JtextPane can be used in the text domain;
Server needs to know which chat content display area sends a message, so the chat content display must be registered on the server. Therefore it must be
Enter the server. To send a message to it, it must have a method that can be called remotely, so it itself has a Remote interface, and Remote
The interface is an empty interface, so we have to write an interface inherited the Remote interface. In this interface, we declare a method that can call on the server:
AppendChatcontent (String MSG). Let's first "get" this interface chatViewerinterface:
Import java.rmi.remote; import java.rmi.remoteexception;
Public Interface ChatViewerinterface Extends Remote {Void AppendChatcontent (String Msg) THROWS RemoteException;
This interface is written. If the server needs more operations, multiple methods can be defined, these methods must throw RemoteException, and then implement this interface.
Next, let's take a look at the chat content display domain ChatViewer code (here, we tie it together with the scroll panel, implement the scroll of chat content):
Import java.rmi. *; import java.rmi.server. *; import javax.swing. *; import java.io. *; import javax.swing.text. *; import javax.swing.text.html. *; Import javax.swing.event. *; import java.text. *;
public class ChatViewer extends JComponent implements ChatViewerInterface, Serializable {JScrollPane scrollpane; JTextPane viewer; public ChatViewer () {this.initializedComponent ();} public ChatViewer (String inimsg) {this.initializedComponent (); this.viewer.setText (inimsg); } private void initializedComponent () {this.viewer = new JTextPane (); this.viewer.setContentType ( "text / html; charset = gb2312"); this.viewer.setEditable (false); this.viewer.addHyperlinkListener (new LinkListener ()); this.scrollpane = new JScrollPane (this.viewer); this.setLayout (new BorderLayout ()); this.add (this.scrollpane, BorderLayout.CENTER);} public void appendChatContent (String msg) {HTMLEditorKit kit = (Htmleditorkit); Document Doc = this.viewer.getdocument (); stringReader Reader = New StringReader (MSG); Try {Kit.Read (Reader, DOC, Doc.getlength ()) Catch (Exception E) {system.out.println ("chat content /" msg "/" lost .. ");} // Automatic scrolling IF (TH Is.Viewer.getSelectedText () == null || this.viewer.getSelectedText (). Trim (). Length () == 0) {this.viewer.select (this.Viewer.getText (). Length (), this.viewer.getText () length ());.}} public void sendToServer () {try {UnicastRemoteObject.exportObject ((ChatViewerInterface) this);} catch (Exception e) {System.out.println ( "send object to Server error: " E.GetMessage ());}}}} class linklistener imports HyperLinkListener {public void hyperlinkupdate (hyperlinkevent e) {if (E.GETEVENTTYPE () ==
HyperlinkEvent.EventType.ACTIVATED) {if (e instanceof HTMLFrameHyperlinkEvent) {HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent) e; HTMLDocument doc = (HTMLDocument) (viewer.getDocument ()); doc.processHTMLFrameHyperlinkEvent (evt);} else {try {Runtime. GetRuntime (). EXEC ("Explorer" E.GETURL ());} catch (exception ooe) {messagedialog.showMessage (null, informations.unsupported_browser);}}}}} // Internal class} here, I introduce The SendtoServer () method is used to serialize its own object to the server side, and the server is registered.
Then we write a window to complete the work of the client. In this class, we have to send messages to the server with a button, the server is also a remote
Object, we name this class ServerforChat, which also implements a remote interface ServerForChatinterface. After writing these code, let's come
Let's take a look at how they work.
Import java.awt. *; import java.awt.event. *; import javax.swing. *;
public class ClientForm extends JFrame {private ChatViewer chat; private JTextField megeditor; private JButton msgsender; private Container contentpane; private JPanel panel; private ServerForChatInterface server;
Public Clientform (String ServerAddress, INT Port) {Super ("Simple Chat Room"); Try {this.server = Naming.lookup ("RMI: //" ServerAddress ": port " / chatserver);} catch (Exception E) {system.out.println ("You cannot connect to the server."); System.exit (0);} this.initializedComponent (); this.fireEvent (); this.registChatViewer ();} private void Initializedcomponent () {This.chat = New chatViewer (" Send message failed, please check the network. b> font>);}} registChatViewer () {try {UnicastRemoteObject.exportObject ((ChatViewerInterface) (this.chat)); this.server.regist ((ChatViewerInterface) (this.chat));} catch (Exception e) {this.chat.appendChatContent (< FONT color = 'red'> <
B> Connection server failed, check the network. b> font>);}}}}} Class Messagesender Implements ActionListener {Public Void ActionPerformed (ActionEvent E) {chat ();}} public static void main (String args [] ) {String ServerAddress = "127.0.0.1"; int port = 1099; if (args! = Null && args.Length == 2) {ServerAddress = args [0]; try {port = integer.parseint (args [1]); } Catch (Exception E) {}} ClientForm Client = New Clientform (ServerAddress, port);}} The client's work is completed, it needs to interact with the server: 1. To the server to register your own chat content display domain object, pass Call the server's Regist (ChatViewerInterface Client) method.
2. It sends a chat message to the server, requested the server to send a message to other online users, by calling the server's CHAT method. So, our server is at least
Includes two remote methods: Regist and chat, we start writing server remote interface ServerForChatinterFace.
Import java.rmi.remote; import java.rmi.remoteexception;
Public Interface ServerForchatinterface Extends Remote {Void Regist (chatviewerinterface client) THROWS RemoteException; Void chatException;}
The server remote interface definition is complete, we start writing the server to implement code.
Import java.rmi. *; import java.rmi.server. *; import java.util.Vector; import java.rmi.registry. *;
public class ServerForChat extends UnicastRemoteObject implements ServerForChatInterface {private static Vector clients = new Vector (); private int port = 1099; public ServerForChat () throws RemoteException {super ();} public ServerForChat (int port) throws RemoteException {super (port); } {if (clients.contains (client) {● {clients.add (client);}} public void chat (string msg) {for (int i = 0; I Compile the above code: Javac (PATH) / *. java rmic -v1.2 chatviewer rmic -v1.2 serverforchat Then we start the server: Java ServerForChat [Port] JVM will start the RMI registry, and save the object to the remote call in the registry, remote JVM, by looking up the RMI registry naming.lookup (String URL) on the network, Find objects on the remote computer JVM, you can use remote objects like using local JVM objects. And through UnicastRemoteObject.export (transote) The local object can be serially serialized directly to the remote JVM, and the remote JVM receives this object, or it can be used in the same way as using the local object. Specific RMI implementation And the concept of residual codes, frame code, etc. can refer to RMI entry related books. It is also worth mentioning that the RMI security mechanism provided by Java, as well as the concept of HTTP tunnel, interested readers can read RMI-related books in detail. Welcome to me Contact, contact mailbox: zlbbq47054370@sina.com