package com.tipcj.demos;

import java.nio.Buffer;
import java.nio.ByteBuffer;

import com.tipcj.*;

public class Hello_Java_Api_Server {
	public static final int SERVER_TYPE  = 18888;
	public static final int SERVER_INST  = 17;
	public static final int BUF_SIZE = 40;

	public static void main(String[] args) {
		ByteBuffer bytebuffer = ByteBuffer.allocateDirect(BUF_SIZE);
		byte[] inbuf = new byte[BUF_SIZE];
		byte[] outbuf = new String("Uh?").getBytes();
		TipcConn serverConn = null;
		int ret;

		System.out.println("****** TIPC hello world server started ******\n");

		/**
		 * Create TipcConn instance
		 */
		serverConn = new TipcConn(SocketType.SOCK_RDM);

		/**
		 * Bind to service instance
		 */
		ret = serverConn.Bind(SERVER_TYPE, SERVER_INST, SERVER_INST, 0);
		if (ret != 0) {
			System.out.println("Server: failed to bind port name");
			serverConn.Close();
			return;
		}

		Integer err = new Integer(0);
		TipcAddr client = new TipcAddr();

		ret = serverConn.Recvfrom(bytebuffer, bytebuffer.capacity(), client, null, err);
		if (ret <= 0) {
			System.out.println("Server: unexpected message");
			return;
		}

		bytebuffer.duplicate().get(inbuf, 0, ret);
		System.out.println("Server: Message received: " + new String(inbuf));

		ret = serverConn.Sendto(outbuf, client);
		if (ret < 0) {
			System.out.println("Server: failed to send");
		}

		System.out.println("Server: Sent response : " + new String(outbuf));
		System.out.println("****** TIPC hello world server finished ******");

		serverConn.Close();
	}
}
