summaryrefslogtreecommitdiffstats
blob: 7814f7136b25f625d32cfc602a684bb5ae52670f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
/*
 * Copyright (c) 2010 Remko Tronçon
 * All rights reserved.
 */
/*
 * Copyright (c) 2010-2012, Isode Limited, London, England.
 * All rights reserved.
 */
package com.isode.stroke.network;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.isode.stroke.base.ByteArray;
import com.isode.stroke.eventloop.Event.Callback;
import com.isode.stroke.eventloop.EventLoop;
import com.isode.stroke.eventloop.EventOwner;

public class JavaConnection extends Connection implements EventOwner {

    private class Worker implements Runnable {

        private final HostAddressPort address_;
        private final List<ByteArray> writeBuffer_ = Collections.synchronizedList(new ArrayList<ByteArray>());

        public Worker(HostAddressPort address) {
            address_ = address;
        }

        public void run() {
            try {
                try {
                    socketChannel_ = SocketChannel.open(
                            new InetSocketAddress(address_.getAddress().getInetAddress(),address_.getPort()));                
                    /* By default, SocketChannels start off in blocking mode, which
                     * isn't what we want
                     */
                    socketChannel_.configureBlocking(false);
                } catch (IOException ex) {
                    handleConnected(true);
                    return;
                }
                handleConnected(false);
                while (!disconnecting_) {
                    while (!writeBuffer_.isEmpty()) {
                        ByteArray data = writeBuffer_.get(0);
                        ByteBuffer byteBuffer = ByteBuffer.wrap(data.getData());
                        try {
                            /* Because the SocketChannel is non-blocking, we have to
                             * be prepared to cope with the write operation not
                             * consuming all of the data
                             */
                            boolean finishedWriting = false;
                            while (!finishedWriting && !disconnecting_) {                     
                                socketChannel_.write(byteBuffer);
                                finishedWriting = (byteBuffer.remaining() == 0);
                                if (!finishedWriting) {
                                    try {
                                        /* Give the output buffer a chance to empty */
                                        Thread.sleep(100);
                                    }
                                    catch (InterruptedException e) {
                                        /* Perhaps someone has set disconnecting_ */
                                    }
                                }
                            }
                        } catch (IOException ex) {
                            disconnecting_ = true;
                            handleDisconnected(Error.WriteError);                    
                        }
                        writeBuffer_.remove(0);
                    }

                    ByteArray data = new ByteArray();
                    try {
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

                        int count = socketChannel_.read(byteBuffer);
                        while (count > 0) {
                            byteBuffer.flip();
                            byte[] result = new byte[byteBuffer.remaining()];
                            byteBuffer.get(result);
                            byteBuffer.compact();
                            for (int i=0; i<result.length; i++) {
                                data.append(result[i]);
                            }
                            count = socketChannel_.read(byteBuffer);
                        }
                        if (count == -1) {
                            /* socketChannel input has reached "end-of-stream", which
                             * we regard as meaning that the socket has been closed 
                             */
                            throw new IOException("socketChannel_.read returned -1");
                        }
                    } catch (IOException ex) {
                        handleDisconnected(Error.ReadError);
                        return;
                    }

                    if (!data.isEmpty()) {
                        handleDataRead(data);
                    }

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        /* We've been woken up, probably to force us to do something.*/
                    }
                }            
                handleDisconnected(null);
            }finally {
                if(socketChannel_ != null) {
                    try {
                        socketChannel_.close();
                    } catch (IOException ex) {
                        /* Do we need to return an error if we're already trying to close? */
                    }
                }
            }
        }

        private void handleConnected(final boolean error) {
            eventLoop_.postEvent(new Callback() {
                public void run() {
                    onConnectFinished.emit(error);
                }
            });
        }

        private void handleDisconnected(final Error error) {
            if (!disconnected_) {
                disconnected_ = true;
                eventLoop_.postEvent(new Callback() {
                    public void run() {
                        onDisconnected.emit(error);
                    }
                });
            }
        }

        private void handleDataRead(final ByteArray data) {
            eventLoop_.postEvent(new Callback() {
                public void run() {
                    onDataRead.emit(data);
                }
            });
        }

        public void write(ByteArray data) {
            writeBuffer_.add(data);
        }
    }

    private JavaConnection(EventLoop eventLoop) {
        eventLoop_ = eventLoop;
    }

    public static JavaConnection create(EventLoop eventLoop) {
        return new JavaConnection(eventLoop);
    }

    @Override
    public void listen() {
        //TODO: needed for server, not for client.
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void connect(HostAddressPort address) {
        worker_ = new Worker(address);
        Thread workerThread = new Thread(worker_);
        workerThread.setDaemon(true);
        workerThread.start();
    }

    @Override
    public void disconnect() {
        disconnecting_ = true;
    }

    @Override
    public void write(ByteArray data) {
        worker_.writeBuffer_.add(data);
    }

    @Override
    public HostAddressPort getLocalAddress() {
        if (socketChannel_ == null) {
            return null;
        }
        Socket socket = socketChannel_.socket();
        if (socket == null) {
            return null;
        }
        return new HostAddressPort(new HostAddress(socket.getLocalAddress()), socket.getLocalPort());        
    }
    
    @Override
    public String toString()
    {
        return "JavaConnection " + 
        (socketChannel_ == null ? "with no socket configured" : "for " + getLocalAddress()) +
        (disconnecting_ ? " (disconnecting)" : "");
    }
    
    private final EventLoop eventLoop_;
    private boolean disconnecting_ = false;
    private boolean disconnected_ = false;
    private SocketChannel socketChannel_;
    private Worker worker_;

}