TcpChannel Wiki
A simple, non-blocking, NIO-based, TCP socket API for Java
Status: Beta
Brought to you by:
balilla
This tutorial will take you through all the features of TcpChannel. The tutorial requires running 2 VMs; one will host the server, the other will host the client.
This is the source code for running the server:
public class Server { public static void main(String[] args) throws IOException { new TcpServer("localhost", 12001, new IReceiver() { @Override public void onChannelConnected(ITcpChannel tcpChannel) { System.out.println("Connected " + tcpChannel); } @Override public void onDataReceived(byte[] data, ITcpChannel source) { System.out.println("Received '" + new String(data) + "' from client " + source); source.sendAsync("Goodbye world!".getBytes()); } @Override public void onChannelClosed(ITcpChannel tcpChannel) { System.out.println("Disconnected " + tcpChannel); } }); System.in.read(); } }
This is the source code for the client:
public class Client { public static void main(String[] args) throws IOException { TcpChannel client = new TcpChannel("localhost", 12001, new IReceiver() { @Override public void onChannelConnected(ITcpChannel tcpChannel) { System.out.println("Connected " + tcpChannel); } @Override public void onDataReceived(byte[] data, ITcpChannel source) { System.out.println("Received '" + new String(data) + "' from server " + source); } @Override public void onChannelClosed(ITcpChannel tcpChannel) { System.out.println("Disconnected " + tcpChannel); } }); client.sendAsync("hello world".getBytes()); System.in.read(); } }
After running all the two programs, you should see the following in the server console:
... Connected TcpChannel [connected local=/127.0.0.1:12001 remote=/127.0.0.1:58102] ... Received 'hello world' from client TcpChannel [connected local=/127.0.0.1:12001 remote=/127.0.0.1:51838] ... Disconnected TcpChannel [connected local=/127.0.0.1:12001 remote=/127.0.0.1:51838]
... and the following in the client console:
... Connected TcpChannel [connected local=/127.0.0.1:58102 remote=localhost/127.0.0.1:12001] ... Received 'Goodbye world!' from server TcpChannel [connected local=/127.0.0.1:58102 remote=localhost/127.0.0.1:12001]