View Javadoc

1   package org.xvsm.remote.tcp;
2   
3   import java.io.BufferedOutputStream;
4   import java.io.IOException;
5   import java.net.InetAddress;
6   import java.net.Socket;
7   import java.net.URI;
8   import java.net.UnknownHostException;
9   
10  import org.xvsm.internal.exceptions.FatalException;
11  import org.xvsm.internal.tasks.Task;
12  import org.xvsm.remote.interfaces.IMarshaller;
13  import org.xvsm.remote.interfaces.ITransportSender;
14  
15  /***
16   * @author Christian Schreiber, Michael Proestler
17   * 
18   */
19  public class TcpTransportSender implements ITransportSender<byte[]> {
20  
21  	/***
22  	 * The Marshaller that is used with this TransportSender.
23  	 */
24  	private IMarshaller<byte[]> marshaller;
25  
26  	/***
27  	 * {@inheritDoc}
28  	 */
29  	private void send(URI uri, Task t) {
30  		try {
31  			byte[] bytes = this.marshaller.marshall(t);
32  			InetAddress ip;
33  
34  			if (InetAddress.getLocalHost().getHostAddress().equals(
35  					uri.getHost())) {
36  				ip = InetAddress.getByName("localhost");
37  			} else {
38  				ip = InetAddress.getByName(uri.getHost());
39  			}
40  			int port = uri.getPort();
41  
42  			Socket socket = new Socket(ip.getHostAddress(), port);
43  			BufferedOutputStream out = new BufferedOutputStream(socket
44  					.getOutputStream());
45  
46  			out.write(bytes);
47  			out.flush();
48  			out.close();
49  		} catch (UnknownHostException e) {
50  			throw new FatalException(e);
51  
52  		} catch (IOException e) {
53  			throw new FatalException(e);
54  
55  		}
56  	}
57  
58  	/***
59  	 * {@inheritDoc}
60  	 */
61  	// @Override
62  	public void setMarshaller(IMarshaller<byte[]> m) {
63  		this.marshaller = m;
64  	}
65  
66  	public void sendRequest(URI uri, Task t) {
67  		this.send(uri, t);
68  
69  	}
70  
71  	public void sendResponse(URI uri, Task t) {
72  		this.send(uri, t);
73  
74  	}
75  }