forked from TimSongCoder/LearnJavaForAndroid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocketChannelDemo.java
More file actions
40 lines (36 loc) · 911 Bytes
/
Copy pathSocketChannelDemo.java
File metadata and controls
40 lines (36 loc) · 911 Bytes
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
import java.nio.channels.SocketChannel;
import java.nio.ByteBuffer;
import java.net.InetSocketAddress;
import java.io.IOException;
public class SocketChannelDemo{
public static void main(String[] args){
SocketChannel sc = null;
try{
sc = SocketChannel.open();
sc.configureBlocking(false);
sc.connect(new InetSocketAddress("localhost", 9999));
while(!sc.finishConnect()){
System.out.println("waiting to finish connection");
}
// connection completed
ByteBuffer buffer = ByteBuffer.allocate(200);
while(sc.read(buffer) >= 0){
buffer.flip();
while(buffer.hasRemaining()){
System.out.print((char)buffer.get());
}
buffer.clear(); // prepare for next reading operation
}
}catch(IOException ioe){
ioe.printStackTrace();
}finally{
if(sc!=null){
try{
sc.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
}
}
}