Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ServerActivity extends Activity {
- private NioSocketAcceptor acceptor;
- private static final int SERVER_PORT = 9123;
- private IoSession session;
- // Set this to false to use object serialization instead of custom codec.
- private static final boolean USE_CUSTOM_CODEC = true;
- private class ServerSessionHandler extends IoHandlerAdapter {
- private final Logger LOGGER = LoggerFactory.getLogger(ServerSessionHandler.class);
- @Override
- public void sessionOpened(IoSession s) {
- session = s;
- // set idle time to 60 seconds
- session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 60);
- }
- @Override
- public void messageReceived(IoSession session, Object message) {
- // client only sends AddMessage. otherwise, we will have to identify
- // its type using instanceof operator.
- AddMessage am = (AddMessage) message;
- String value = am.getValue();
- EditText et = (EditText)findViewById(R.id.messageBoard);
- et.append(value);
- }
- @Override
- public void sessionIdle(IoSession session, IdleStatus status) {
- //LOGGER.info("Disconnecting the idle.");
- // disconnect an idle client
- session.close(true);
- }
- @Override
- public void exceptionCaught(IoSession session, Throwable cause) {
- // close the connection on exceptional situation
- session.close(true);
- }
- }
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_server);
- }
- public void startServerButtonClicked(View v){
- acceptor = new NioSocketAcceptor();
- acceptor.getSessionConfig().setReadBufferSize(2048);
- // Prepare the service configuration.
- if (USE_CUSTOM_CODEC) {
- acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MessageProtocolCodecFactory(true)));
- } else {
- acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
- }
- acceptor.getFilterChain().addLast("logger", new LoggingFilter());
- acceptor.setHandler(new ServerSessionHandler());
- try {
- acceptor.bind(new InetSocketAddress(SERVER_PORT));
- } catch (IOException e) {
- e.printStackTrace();
- }
- Log.d("***************************", "Listening on port " + SERVER_PORT);
- }
- public void sendMessageButtonClicked(View v){
- if (session == null){
- Log.d("***************************", "Session is null");
- return;
- }
- ResultMessage rm = new ResultMessage();
- rm.setSequence(1); // copy sequence
- EditText et = (EditText)findViewById(R.id.message);
- rm.setValue(et.getText().toString());
- rm.setOk(true);
- session.write(rm);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement