Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: konspire/common/MessageSender.java


1   // Jason Rohrer
2   // MessageSender.java
3   
4   /**
5   *
6   *  Class for sending reliable socket messages on non-maintained sockets
7   *
8   *  Created 5-2-2000
9   *  Mods:
10  */
11  
12  
13  package konspire.common;
14  
15  import java.io.*;
16  import java.net.*;
17  
18  /**
19   * Class for sending reliable messages on non-maintained sockets.
20   * <p>
21   * Each send method call creates a <code>Socket</code>, sends the <code>Message</code>,
22   * and then closes the <code>Socket</code>.
23   *
24   * @author Jason Rohrer
25   */
26  public class MessageSender {
27    
28    /**
29     * Sends a single <code>Message</code> to a specified <code>Host</code>.
30     *
31     * @param m the <code>Message</code> to send
32     * @param h the <code>Host</code> to send the message to
33     *
34     * @return true iff send completes successfully
35     */
36    public boolean sendMessage( Message m, Host h ) {
37      try {
38        try {
39          Socket sock = new Socket( h.getAddress(), h.getPort() );
40  
41          DataOutputStream output = new DataOutputStream( sock.getOutputStream() );
42          
43          DataInputStream input = new DataInputStream( sock.getInputStream() );
44  
45                  
46          ObjectOutputStream objStream = new ObjectOutputStream( output );
47          ObjectInputStream objInStream = new ObjectInputStream( input );
48          
49          
50          objStream.writeObject( m );
51          
52          objStream.flush();
53          
54          objStream.close();
55          
56          output.flush();
57          
58          output.close();
59          sock.close();
60          
61          return true;    // message sent successfully
62          }
63        catch( UnknownHostException e ) {
64          return false;
65          }
66        }
67      catch( IOException e ) {
68        return false;
69        }
70      }
71        
72    }