Biblioteca Java - Blame information for rev 3
Subversion Repositories:
Rev | Author | Line No. | Line |
---|---|---|---|
3 | mihai | 1 | /* |
2 | * Created on Jan 13, 2007 | ||
3 | * | ||
4 | * TODO To change the template for this generated file go to | ||
5 | * Window - Preferences - Java - Code Style - Code Templates | ||
6 | */ | ||
7 | package lab.scd.net.neblocant1; | ||
8 | |||
9 | import java.io.*; | ||
10 | import java.nio.*; | ||
11 | import java.nio.channels.*; | ||
12 | import java.nio.channels.spi.*; | ||
13 | import java.nio.charset.*; | ||
14 | import java.net.*; | ||
15 | import java.util.*; | ||
16 | /** | ||
17 | * @author mihai | ||
18 | * | ||
19 | * TODO To change the template for this generated type comment go to | ||
20 | * Window - Preferences - Java - Code Style - Code Templates | ||
21 | */ | ||
22 | public class NonBlockingClient { | ||
23 | |||
24 | |||
25 | public static void main(String[] args) throws IOException { | ||
26 | |||
27 | |||
28 | // Create client SocketChannel | ||
29 | SocketChannel client = SocketChannel.open(); | ||
30 | |||
31 | // nonblocking I/O | ||
32 | client.configureBlocking(false); | ||
33 | |||
34 | // Connection to host port 8000 | ||
35 | client.connect(new java.net.InetSocketAddress("localhost",8000)); | ||
36 | |||
37 | // Create selector | ||
38 | Selector selector = Selector.open(); | ||
39 | |||
40 | // Record to selector (OP_CONNECT type) | ||
41 | SelectionKey clientKey = client.register(selector, SelectionKey.OP_CONNECT); | ||
42 | |||
43 | // Waiting for the connection | ||
44 | while (selector.select(500)> 0) { | ||
45 | |||
46 | System.err.println("Start communication..."); | ||
47 | |||
48 | // Get keys | ||
49 | Set keys = selector.selectedKeys(); | ||
50 | Iterator i = keys.iterator(); | ||
51 | |||
52 | // For each key... | ||
53 | while (i.hasNext()) { | ||
54 | SelectionKey key = (SelectionKey)i.next(); | ||
55 | |||
56 | // Remove the current key | ||
57 | i.remove(); | ||
58 | |||
59 | // Get the socket channel held by the key | ||
60 | SocketChannel channel = (SocketChannel)key.channel(); | ||
61 | |||
62 | // Attempt a connection | ||
63 | if (key.isConnectable()) { | ||
64 | |||
65 | // Connection OK | ||
66 | System.out.println("Server Found"); | ||
67 | |||
68 | // Close pendent connections | ||
69 | if (channel.isConnectionPending()) | ||
70 | channel.finishConnect(); | ||
71 | |||
72 | // Write continuously on the buffer | ||
73 | ByteBuffer buffer = null; | ||
74 | int x=0; | ||
75 | for (;x<7;) { | ||
76 | x++; | ||
77 | buffer = | ||
78 | ByteBuffer.wrap( | ||
79 | new String(" Client " + x + " "+x).getBytes()); | ||
80 | channel.write(buffer); | ||
81 | buffer.clear(); | ||
82 | try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();} | ||
83 | } | ||
84 | channel.finishConnect(); | ||
85 | client.close(); | ||
86 | } | ||
87 | } | ||
88 | } | ||
89 | System.err.println("Client terminated."); | ||
90 | } | ||
91 | } |