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