Tutorials     About     RSS
Tech and Media Labs

Grid Ops Java - TcpServer

Jakob Jenkov
Last update: 2016-10-08

One of the core components of Grid Ops is the TCP server components. The TCP server needs 2 threads to run. The first thread runs the accept loop which accepts new incoming connections. The second thread reads data from all the incoming connections and do whatever you want to do with the incoming traffic.

Creating a TCP Server

Here is how you create a simple TCP server in Grid Ops:

TcpServer tcpServer  = GridOps.tcpServerBuilder().build();

This creates a TcpServerBuilder and builds the TCP server by calling build() on the TcpServerBuilder();

The above example opens the TCP port on port 1111 which is the default IAP port.

Setting TCP Port

You can set the TCP port for the TCP server when building it. Here is an example of how to set the TCP port on a TCP server:

 TcpServer tcpServer  = GridOps.tcpServerBuilder().tcpPort(1111).build();

It is the method call tcpPort(1111) on the TCP server builder which sets the TCP port the server will listen on.

Starting the TCP Server

The previous code example only creates a TCP server, but it does not start it. You can start a thread that listens for incoming connections for the TCP server like this:

TcpServer tcpServer  = GridOps.tcpServerBuilder().build();

new Thread(tcpServer).start();

The second line of this code example starts a new thread which runs the TCP server's run() method.

Now the newly created thread listens for incoming connections, but this thread does not read any data from the incoming connections.

The TCP server builder also has a convenience method that starts a thread for the TCP server which listens for incoming connections. Here is how using that convenience method looks:

TcpServer tcpServer = GridOps.tcpServerBuilder().buildAndStart();

It is the buildAndStart() method that first builds the TcpServer instance and then starts a thread to listen for incoming connections for it. Of course you can still call tcpPort() on the TCP server builder before calling buildAndStart().

Reading Messages From the TCP Server

To read messages from the TCP server you need to create a TcpSocketsPort instance. Doing so is explained in its own text.

Stopping the TCP Server

You can stop a running TCP server by calling its stop() method, like this:


This will cause the thread listening for incoming connections to close the ServerSocketChannel and make the thread exit. It does not currently take any open inbound sockets into consideration.

Jakob Jenkov

Featured Videos

Thread Congestion in Java - Video Tutorial

Sponsored Ads

Maildroppa - Smart Email Marketing Solution
Close TOC

All Trails

Trail TOC

Page TOC