1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.example.tcp.perf;
21
22 import java.net.InetSocketAddress;
23
24 import org.apache.mina.core.buffer.IoBuffer;
25 import org.apache.mina.core.future.ConnectFuture;
26 import org.apache.mina.core.future.WriteFuture;
27 import org.apache.mina.core.service.IoConnector;
28 import org.apache.mina.core.service.IoHandlerAdapter;
29 import org.apache.mina.core.session.IdleStatus;
30 import org.apache.mina.core.session.IoSession;
31 import org.apache.mina.transport.socket.SocketSessionConfig;
32 import org.apache.mina.transport.socket.nio.NioSocketConnector;
33
34
35
36
37
38
39
40
41
42 public class TcpClient extends IoHandlerAdapter {
43
44 private IoConnector connector;
45
46
47 private static IoSession session;
48
49 private boolean received = false;
50
51
52
53
54 public TcpClient() {
55 connector = new NioSocketConnector();
56
57 connector.setHandler(this);
58 SocketSessionConfig dcfg = (SocketSessionConfig) connector.getSessionConfig();
59
60 ConnectFuture connFuture = connector.connect(new InetSocketAddress("localhost", TcpServer.PORT));
61
62 connFuture.awaitUninterruptibly();
63
64 session = connFuture.getSession();
65 }
66
67
68
69
70 @Override
71 public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
72 cause.printStackTrace();
73 }
74
75
76
77
78 @Override
79 public void messageReceived(IoSession session, Object message) throws Exception {
80 received = true;
81 }
82
83
84
85
86 @Override
87 public void messageSent(IoSession session, Object message) throws Exception {
88 }
89
90
91
92
93 @Override
94 public void sessionClosed(IoSession session) throws Exception {
95 }
96
97
98
99
100 @Override
101 public void sessionCreated(IoSession session) throws Exception {
102 }
103
104
105
106
107 @Override
108 public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
109 }
110
111
112
113
114 @Override
115 public void sessionOpened(IoSession session) throws Exception {
116 }
117
118
119
120
121
122
123
124 public static void main(String[] args) throws Exception {
125 TcpClient client = new TcpClient();
126
127 long t0 = System.currentTimeMillis();
128
129 for (int i = 0; i <= TcpServer.MAX_RECEIVED; i++) {
130
131
132
133
134 IoBuffer buffer = IoBuffer.allocate(4);
135 buffer.putInt(i);
136 buffer.flip();
137 WriteFuture future = session.write(buffer);
138
139 while (client.received == false) {
140 Thread.sleep(1);
141 }
142
143 client.received = false;
144
145 if (i % 10000 == 0) {
146 System.out.println("Sent " + i + " messages");
147 }
148 }
149
150 long t1 = System.currentTimeMillis();
151
152 System.out.println("Sent messages delay : " + (t1 - t0));
153
154 Thread.sleep(100000);
155
156 client.connector.dispose(true);
157 }
158 }