View Javadoc

1   package org.neo.swarm.util.network.tcp.client;
2   import java.io.IOException;
3   import java.net.InetAddress;
4   import java.net.InetSocketAddress;
5   import java.nio.ByteBuffer;
6   import java.nio.channels.SocketChannel;
7   
8   import org.neo.swarm.util.io.StreamCallback;
9   
10  public class SocketReader implements StreamCallback {
11  	private InetAddress address;
12  	private int port;
13  	private SocketChannel sc;
14  	private boolean blocking;
15  	
16  	public SocketReader(InetAddress host, int port, boolean blocking) {
17  		this.address = host;
18  		this.port = port;
19  		this.blocking = blocking;
20  		try {
21  			connect();
22  		} catch (IOException e) {
23  			e.printStackTrace();
24  		}
25  	}
26  	public SocketReader(InetAddress host, int port, SocketChannel sc) {
27  		this.address = host;
28  		this.port = port;
29  		this.sc = sc;
30  	}
31  	/*
32  	 * (non-Javadoc)
33  	 * 
34  	 * @see org.neo.swarm.util.io.StreamCallback#setByteBuffer(java.nio.ByteBuffer)
35  	 */
36  	public void connect() throws java.io.IOException {
37  		sc = SocketChannel.open();
38  		sc.configureBlocking(this.blocking);
39  		sc.connect(new InetSocketAddress(this.address, this.port));
40  		sc.finishConnect();
41  	}
42  	public void disconnect() throws IOException {
43  		sc.close();
44  	}
45  	
46  	public synchronized int execute(ByteBuffer buffer, int bytes) throws IOException {
47  
48  			if (!sc.isConnected()) {
49  				connect();
50  			}
51  			return this.sc.read(buffer);
52  	}
53  
54  	/* (non-Javadoc)
55  	 * @see org.neo.swarm.util.io.StreamCallback#close()
56  	 */
57  	public void close() {
58  		try {
59  			this.sc.socket().shutdownInput();
60  			this.sc.close();
61  		} catch (IOException e) {
62  			e.printStackTrace();
63  		}
64  		
65  	}
66  }