본문 바로가기
Study/Android

Nio udp Client (비동기 UDP Client)

by Answer Choi 2015. 2. 11.
반응형




 

 

테스트는 클라이언트(안드로이드)-서버(docklight)를 이용했습니다.

 

 

 

MainActivity.java


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
 @Override
    public void onClick(View v) {
        switch(v.getId()){
       
        case R.id.connect:
            String ip=ipaddr.getText().toString();
            int portNum=Integer.parseInt(port.getText().toString());
           
            try{
                client=new UdpClient(ip,portNum);
            }catch(IOException e){
                e.printStackTrace();
            }
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);  
            imm.hideSoftInputFromWindow(ipaddr.getWindowToken(), 0);
            client.start();
            connect.setEnabled(false);
            disconnect.setEnabled(true);
            text.setText("Connected\n");
             break;
        case R.id.disconnect:
           
            connect.setEnabled(true);
            disconnect.setEnabled(false);  
            text.setText("Disconnected\n");
            break;
       
        case R.id.sendBtn:
            String message;
            message=msg.getText().toString();
            Message m=new Message();
            m.what=MSG;
            m.obj="Client : "+message;
            mHandler.sendMessage(m);
            sendingMsg(message);
           
            break;
       
        default:
        break;
        }
       
    }
 
cs


Line 5~20 : 이부분은 연결하기


Line 10 : 네트워크(datagram) 객체 생성합니다.


Line 16 : 스레드 스타트~


Line 21~26 : 이부분은연결 끊기


Line 28~37 : 이 부분은 메세지 보내기

 

udpclient.java (읽는 부분)


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
public class UdpClient extends Thread {
    MainActivity main;
    private final String hostAddress;
    private int port=5000;
    public static final int BUFFER_SIZE=2048;
    public final static int DEFAULT_PORT=5000;
   
    private Boolean loop;
    private static final long TIME_OUT=1000;
   
    public static DatagramChannel channel=null;
   
    public UdpClient(String Addr,int port) throws IOException{
    this.hostAddress=Addr;
    this.port=port;
   
    MainActivity.thread=new HandlerThread("HandlerThread",Process.THREAD_PRIORITY_BACKGROUND);
    MainActivity.thread.start();
    Looper mLooper=MainActivity.thread.getLooper();
    MainActivity.mServicehandler=new ServiceHandler(mLooper);
    
    channel=DatagramChannel.open();
    MainActivity.selector=Selector.open();
   
    }
 
   
    @Override
    public void run() {
       
       
        try{
            final ByteBuffer readBuffer=ByteBuffer.allocate(BUFFER_SIZE);
            channel.configureBlocking(false);
            channel.connect(new InetSocketAddress(hostAddress, port));
            channel.register(MainActivity.selector, SelectionKey.OP_READ);
           
           
           
           
            loop=true;
            while(loop){
               
                Log.e("chk""before");
                if(MainActivity.selector.select(TIME_OUT)==0)
                    continue;
               
                Set<SelectionKey> readKeys=MainActivity.selector.selectedKeys();
                Iterator<SelectionKey> iterator=readKeys.iterator();
                Log.e("chk""after");
                while(iterator.hasNext()){
                   
                    SelectionKey key=iterator.next();
                    iterator.remove();
                   
                    if(key.isReadable()){
                        readBuffer.clear();
                        int length=channel.read(readBuffer);
                        readBuffer.flip();
                        byte[] receivedData=new byte[length];
                        System.arraycopy(readBuffer.array(), 0, receivedData,0length);
                        String line=new String(receivedData);
                       
                        Message m2=new Message();
                        m2.what=MainActivity.MSG;
                        m2.obj="Server : "+line;
                        if(m2.obj!=null)
                        MainActivity.mHandler.sendMessage(m2);
                    }
                }
            }
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            try{
                channel.close();
            }catch(IOException e){
                e.printStackTrace();
            }
           
        }
    }
    public void quit(){
        loop=false;
        try{
            channel.close();
        }catch(IOException e){
           
        }
        MainActivity.thread.quit();
        MainActivity.thread.interrupt();
    }
}
cs


Line 17~20 : 핸들러 스레드를 생성해주고 스타트합니다.(이건 메세지 보내기용입니다.)


Line 22~23 : datagramchannel과 selector를 만들어주고요~


Line 34 : datagramchannel을 넌블럭(nio)로 설정


Line 35 : 그리고 서버에 연결합니다.


Line 36 : Selector는 읽기모드로~


Line 42~71 : 이부분이 읽는 부분입니다.


Line 48~49 : 여기는 selector가 이벤트를 감지하면(패킷이 들어오면), iterator로 전달.


Line 57~62 : 그리고 읽습니다.


Line 64~68 : 읽었으니 뿌려줍니다.


Line 83~92 : 요부분은 연결끊기!!

 

ServiceHandler.java(쓰는부분)

 

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
public final class ServiceHandler extends Handler{
    private final ByteBuffer writeBuffer;
   
   
    public ServiceHandler(Looper looper){
        super(looper);
        writeBuffer=ByteBuffer.allocate(UdpClient.BUFFER_SIZE);
    }
 
    @Override
    public void handleMessage(Message msg) {
        writeBuffer.clear();
        String s=(String)msg.obj;
        writeBuffer.put(s.getBytes());
       
        writeBuffer.flip();
        try{
            UdpClient.channel.write(writeBuffer);
        }catch(IOException e){
            e.printStackTrace();
        }
        super.handleMessage(msg);
    }
   
   
}
cs


Line 10~23 : 여긴 메세지를 써서 전달하는부분(mainactivity.java에서 send 버튼 눌렀을때 이벤트 발생합니다.)


반응형

인기글