aboutsummaryrefslogtreecommitdiffstats
path: root/AndroidAsync/src/com/koushikdutta/async/DatagramChannelWrapper.java
blob: 9d3c84c4674be862b25c4e0ff556b5aa7da67afa (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
package com.koushikdutta.async;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;

class DatagramChannelWrapper extends ChannelWrapper {
    DatagramChannel mChannel;
    
    @Override
    public int getLocalPort() {
        return mChannel.socket().getLocalPort();
    }

    InetSocketAddress address;
    public InetSocketAddress getRemoteAddress() {
        return address;
    }
    
    public void disconnect() throws IOException {
        mChannel.disconnect();
    }
    
    DatagramChannelWrapper(DatagramChannel channel) throws IOException {
        super(channel);
        mChannel = channel;
    }
    @Override
    public int read(ByteBuffer buffer) throws IOException {
        if (!isConnected()) {
            int position = buffer.position();
            address = (InetSocketAddress)mChannel.receive(buffer);
            if (address == null)
                return -1;
            return buffer.position() - position;
        }
        address = null;
        return mChannel.read(buffer);
    }
    @Override
    public boolean isConnected() {
        return mChannel.isConnected();
    }
    @Override
    public int write(ByteBuffer src) throws IOException {
        return mChannel.write(src);
    }
    @Override
    public int write(ByteBuffer[] src) throws IOException {
        return (int)mChannel.write(src);
    }
    @Override
    public SelectionKey register(Selector sel, int ops) throws ClosedChannelException {
        return mChannel.register(sel, ops);
    }
    @Override
    public boolean isChunked() {
        return true;
    }
    @Override
    public SelectionKey register(Selector sel) throws ClosedChannelException {
        return register(sel, SelectionKey.OP_READ);
    }

    @Override
    public void shutdownOutput() {
    }

    @Override
    public void shutdownInput() {
    }

    @Override
    public long read(ByteBuffer[] byteBuffers) throws IOException {
        return mChannel.read(byteBuffers);
    }

    @Override
    public long read(ByteBuffer[] byteBuffers, int i, int i2) throws IOException {
        return mChannel.read(byteBuffers, i, i2);
    }

    @Override
    public Object getSocket() {
        return mChannel.socket();
    }
}