Implements the lowest lever layer which allows to open a socket in a certain IP and port. At the same time, the service runs in the execution time in a Axional Studio already running. Create and start the service.

1 socket.addServiceClass

<socket.addServiceClass
    name='name'
    host='host'
    port='port'
    backlog='backlog'
    so-rcvbuf='so-rcvbuf'
    log-time='log-time'
>
    <Service Class /> +
</socket.addServiceClass>
Example

The following example shows how a socket service is created and how it runs. To test it, a socket client which sends a message to the service is declared. The service print on screen the answer and then, the service stops.

Copy
<xsql-script name='addServiceClass'>
 <body>
  <socket.addServiceClass name='echo' host='127.0.0.1' port='5555' backlog='5' so-rcvbuf='128' log-time='5'>
<![CDATA[
      public class echo extends NioService
      {
            private int READ_MESSAGE_WAIT_TIME  = 10;
            private int WRITE_MESSAGE_WAIT_TIME = 10;
            
        	@Override
        	public void handleAcceptConnection(AsynchronousSocketChannel asyncSocketChannel)
        		throws Exception
        	{
        		ByteBuffer messageByteBuffer = ByteBuffer.allocate(getMessageReadSize());
        		// read a message from the client, timeout after 10 seconds
        		Future<Integer> futureReadResult = asyncSocketChannel.read(messageByteBuffer);
        		futureReadResult.get(READ_MESSAGE_WAIT_TIME, TimeUnit.SECONDS);
        
        		String clientMessage = new String(messageByteBuffer.array()).trim();
        		messageByteBuffer.clear();
        		messageByteBuffer.flip();
        
        		String responseString = "echo:" + clientMessage + "\n";
        		messageByteBuffer = ByteBuffer.wrap((responseString.getBytes()));
        		Future<Integer> futureWriteResult = asyncSocketChannel.write(messageByteBuffer);
        		futureWriteResult.get(WRITE_MESSAGE_WAIT_TIME, TimeUnit.SECONDS);
        		if (messageByteBuffer.hasRemaining()) {
        			messageByteBuffer.compact();
        		} else {
        			messageByteBuffer.clear();
        		}
        	}
      }        
] ]>
  </socket.addServiceClass>
  
  <!-- TEST CLIENT -->
  
  <!-- declare a socket to connecto to echo server -->
  <set name='m_socket'>
   <socket host='127.0.0.1' port='5555' timeout='2' />
  </set>
  
  <!-- send a message to echo -->
   <println>
    SEND:
    <socket.out.println>
     <m_socket />
     <string>Hello from client</string>
    </socket.out.println>
   </println>
  
  <!-- read response from echo -->
  <println>
    RECV:
    <socket.in.readLine>
     <m_socket />
    </socket.in.readLine>
   </println>
  
  <!-- close the client socket -->
  <socket.close><m_socket/></socket.close>
  
  <!-- stop socket server -->
  <socket.stopServiceClass name='echo' />
 </body>
</xsql-script>