Simple Socket Client

I've posted examples of a socket client and server that provide a simple message switch in the past. May people have found these examples too complex and the most recent is Java 5 only. The simple client was lost some time ago, so I'm reposting it in an even simpler form. It uses three threads,
- the AWT Event Dispatch Thread used by Swing
- a thread that reads text lines and posts them to the GUI using invokeLater
- a thread that sends text lines from a queue.
This code is compatible with:
- Simple Socket Server
- Socket Example using Java 5
//================= SimpleClient.java ==========================================//
* a Simple swing GUI that can communicate with either the SimpleServer or
* the servers in the pkwnet package.
* @author PKWooster
* @version 1.0 Dec 10,2005
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.LinkedList;
public class SimpleClient {
    private JFrame frame = new JFrame("Simple Client");
    private JTextField userText = new JTextField(40);          // input text
     private JTextArea display = new JTextArea(24,40);          // display window
     private JTextField statusText = new JTextField(40);          // status
     private JPanel outPanel = new JPanel();
     private JScrollPane displayScroll = new JScrollPane(display);
     private JMenuBar menuBar = new JMenuBar();
     private JMenuItem startItem = new JMenuItem("Start");
     private JMenuItem hostItem = new JMenuItem("Host");
     private JMenuItem exitItem = new JMenuItem("Exit");
     private JMenu fileMenu = new JMenu("File");
     private JMenu helpMenu = new JMenu("Help");
     private Container cp;
    private volatile int state = CLOSED;
     private String address="127.0.0.1:5050";
    private static final int CLOSED = 0;
    private static final int OPENING = 1;
    private static final int OPENED = 2;
    private static final int CLOSING = 3;
    private String host;
    private int port;
    private Socket sock;
    private BufferedReader in;
    private BufferedWriter out;
    private Thread recvThread;
    private Thread sendThread;
    private String name;
    private LinkedList sendQueue = new LinkedList();
* construct the SimpleClient
    SimpleClient(String address) {
        this.address = address;
          startItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                mnuStart();
          fileMenu.add(startItem);
          hostItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                mnuHost();
          fileMenu.add(hostItem);
          exitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                mnuExit();
          fileMenu.add(exitItem);
          menuBar.add(fileMenu);
          menuBar.add(helpMenu);
          frame.setJMenuBar(menuBar);
        cp = frame.getContentPane();
          display.setEditable(false);
          outPanel.add(new JLabel("Send: "));
          outPanel.add(userText);
          // enter on userText causes transmit
          userText.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent evt) {
                userTyped(evt);
          cp.setLayout(new BorderLayout());
          cp.add(outPanel,BorderLayout.NORTH);
          cp.add(displayScroll,BorderLayout.CENTER);
          cp.add(statusText,BorderLayout.SOUTH);
          setStatus("Closed");
          frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent evt) {
                mnuExit();
        frame.pack();
        frame.setVisible(true);
* user pressed enter in the user text field, we try to send the text
    private void userTyped(ActionEvent evt) {
          String txt = evt.getActionCommand()+"\n";
          userText.setText("");     // don't send it twice
          toDisplay(txt);
          if(state == OPENED) {
            send(txt);
     private void toDisplay(String txt) {
          display.append(txt);
          display.setCaretPosition(display.getDocument().getLength() );
    private void setState(int s) {
        state = s;
        if (SwingUtilities.isEventDispatchThread()) {
            showState();
        } else {
            SwingUtilities.invokeLater(new Runnable() {
                public void run(){
                    showState();
    private void postReceive(final String msg) {
        if (SwingUtilities.isEventDispatchThread()) {
            toDisplay(msg);
        } else {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    toDisplay(msg);
* start and stop connection
     private void mnuStart() {
        if (state == CLOSED) {
            setState(OPENING);
            connect(address);
        } else {
            close();
* prompt user for host in form address:port
* default is 127.0.0.1:5050
     private void mnuHost(){
          String txt = JOptionPane.showInputDialog("Enter host address and port",address+":"+port);
          if (txt != null) {
            address = txt;
     // exit menu
     private void mnuExit() {
          close();     
          System.exit(0);
     private void showState () {
        switch(state) {
            case OPENED:
                startItem.setText("Stop");
                setStatus("Connected to "+address);
                break;
            case CLOSED:
                startItem.setText("Start");
                setStatus("Disconnected");
                break;
            case OPENING:
                setStatus("Connecting to "+address);
                startItem.setText("Abort");
                break;
            case CLOSING:
                setStatus("Disconnecting from "+address);
                startItem.setText("Abort");
                break;
     private void setStatus(String st) {
        statusText.setText(st);
    static public void main(String [] args) {
        String address = "127.0.0.1:5050";
        for(int i = 0; i<args.length; i++) {
            address = args;
final String hostAddress = address;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
SimpleClient client = new SimpleClient(hostAddress);
* connect to a remote host
private void connect(String address) {
setState(OPENING);
parseAddress(address);
sendThread = new Thread(new Runnable() {
public void run() {
doConnect();
if (OPENED == state) {
doSend();
sendThread.start();
private void send(String data) {
synchronized(sendQueue) {
sendQueue.add(data);
sendQueue.notifyAll();
* the main loop for the send thread
private void doSend() {
String msg = null;
while (OPENED == state && null != (msg = waitToSend())) {
try {
out.write(msg);
out.flush();
} catch(IOException e) {
e.printStackTrace();
setState(CLOSING);
close();
System.out.println("Thread="+Thread.currentThread().getName()+" ending");
* connect to a remote host
private void doConnect() {
try {
sock = new Socket(host, port);
name = ""+sock.getInetAddress()+":"+sock.getPort();
Thread.currentThread().setName("Send."+name);
in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
recvThread = new Thread(new Runnable() {
public void run() {
doRecv();
},"Recv."+name);
recvThread.start();
setState(OPENED);
} catch (IOException e) {
setState(CLOSED);
private void parseAddress(String txt) {
String ps = "";
int n = txt.indexOf(':');
          if(n == 0) {
               address = "127.0.0.1";
ps = txt.substring(1);
          } else if (n < 0) {
               address = txt;
               ps = "5050";
          } else {
               address = txt.substring(0,n);
               ps = txt.substring(n+1);
try {
port = Integer.parseInt(ps);
} catch(NumberFormatException e) {
port = 5050;
* get the connection name
public String getName(){return name;}
* the main loop for the receive thread
private void doRecv() {
String inbuf;
while (CLOSED != state) {
try {
inbuf = in.readLine();
} catch(Exception e) {
System.out.println(e);
inbuf = null;
if(inbuf == null) {
close();
} else {
postReceive(inbuf+"\r\n");
System.out.println("Thread="+Thread.currentThread().getName()+" ending");
private void close() {
if(state == OPENED) {
setState(CLOSING);
try {
sock.shutdownOutput();
} catch(IOException ie) {
ie.printStackTrace();
close();
} else if (state != CLOSED) {
try {
if (null != out) {
out.close();
if (null != in) {
in.close();
if (null != sock) {
sock.close();
}catch (Exception e) {
e.printStackTrace();
if (sendThread.isAlive()) {
sendThread.interrupt();
setState(CLOSED);
private String waitToSend() {
String msg = null;
synchronized(sendQueue) {
try {
while (sendQueue.isEmpty()) {
sendQueue.wait();
msg = (String)sendQueue.remove();
} catch (InterruptedException e) {
e.printStackTrace();
return msg;

I've posted examples of a socket client and server that provide a simple message switch in the past. May people have found these examples too complex and the most recent is Java 5 only. The simple client was lost some time ago, so I'm reposting it in an even simpler form. It uses three threads,
- the AWT Event Dispatch Thread used by Swing
- a thread that reads text lines and posts them to the GUI using invokeLater
- a thread that sends text lines from a queue.
This code is compatible with:
- Simple Socket Server
- Socket Example using Java 5
//================= SimpleClient.java ==========================================//
* a Simple swing GUI that can communicate with either the SimpleServer or
* the servers in the pkwnet package.
* @author PKWooster
* @version 1.0 Dec 10,2005
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.LinkedList;
public class SimpleClient {
    private JFrame frame = new JFrame("Simple Client");
    private JTextField userText = new JTextField(40);          // input text
     private JTextArea display = new JTextArea(24,40);          // display window
     private JTextField statusText = new JTextField(40);          // status
     private JPanel outPanel = new JPanel();
     private JScrollPane displayScroll = new JScrollPane(display);
     private JMenuBar menuBar = new JMenuBar();
     private JMenuItem startItem = new JMenuItem("Start");
     private JMenuItem hostItem = new JMenuItem("Host");
     private JMenuItem exitItem = new JMenuItem("Exit");
     private JMenu fileMenu = new JMenu("File");
     private JMenu helpMenu = new JMenu("Help");
     private Container cp;
    private volatile int state = CLOSED;
     private String address="127.0.0.1:5050";
    private static final int CLOSED = 0;
    private static final int OPENING = 1;
    private static final int OPENED = 2;
    private static final int CLOSING = 3;
    private String host;
    private int port;
    private Socket sock;
    private BufferedReader in;
    private BufferedWriter out;
    private Thread recvThread;
    private Thread sendThread;
    private String name;
    private LinkedList sendQueue = new LinkedList();
* construct the SimpleClient
    SimpleClient(String address) {
        this.address = address;
          startItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                mnuStart();
          fileMenu.add(startItem);
          hostItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                mnuHost();
          fileMenu.add(hostItem);
          exitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                mnuExit();
          fileMenu.add(exitItem);
          menuBar.add(fileMenu);
          menuBar.add(helpMenu);
          frame.setJMenuBar(menuBar);
        cp = frame.getContentPane();
          display.setEditable(false);
          outPanel.add(new JLabel("Send: "));
          outPanel.add(userText);
          // enter on userText causes transmit
          userText.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent evt) {
                userTyped(evt);
          cp.setLayout(new BorderLayout());
          cp.add(outPanel,BorderLayout.NORTH);
          cp.add(displayScroll,BorderLayout.CENTER);
          cp.add(statusText,BorderLayout.SOUTH);
          setStatus("Closed");
          frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent evt) {
                mnuExit();
        frame.pack();
        frame.setVisible(true);
* user pressed enter in the user text field, we try to send the text
    private void userTyped(ActionEvent evt) {
          String txt = evt.getActionCommand()+"\n";
          userText.setText("");     // don't send it twice
          toDisplay(txt);
          if(state == OPENED) {
            send(txt);
     private void toDisplay(String txt) {
          display.append(txt);
          display.setCaretPosition(display.getDocument().getLength() );
    private void setState(int s) {
        state = s;
        if (SwingUtilities.isEventDispatchThread()) {
            showState();
        } else {
            SwingUtilities.invokeLater(new Runnable() {
                public void run(){
                    showState();
    private void postReceive(final String msg) {
        if (SwingUtilities.isEventDispatchThread()) {
            toDisplay(msg);
        } else {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    toDisplay(msg);
* start and stop connection
     private void mnuStart() {
        if (state == CLOSED) {
            setState(OPENING);
            connect(address);
        } else {
            close();
* prompt user for host in form address:port
* default is 127.0.0.1:5050
     private void mnuHost(){
          String txt = JOptionPane.showInputDialog("Enter host address and port",address+":"+port);
          if (txt != null) {
            address = txt;
     // exit menu
     private void mnuExit() {
          close();     
          System.exit(0);
     private void showState () {
        switch(state) {
            case OPENED:
                startItem.setText("Stop");
                setStatus("Connected to "+address);
                break;
            case CLOSED:
                startItem.setText("Start");
                setStatus("Disconnected");
                break;
            case OPENING:
                setStatus("Connecting to "+address);
                startItem.setText("Abort");
                break;
            case CLOSING:
                setStatus("Disconnecting from "+address);
                startItem.setText("Abort");
                break;
     private void setStatus(String st) {
        statusText.setText(st);
    static public void main(String [] args) {
        String address = "127.0.0.1:5050";
        for(int i = 0; i<args.length; i++) {
            address = args;
final String hostAddress = address;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
SimpleClient client = new SimpleClient(hostAddress);
* connect to a remote host
private void connect(String address) {
setState(OPENING);
parseAddress(address);
sendThread = new Thread(new Runnable() {
public void run() {
doConnect();
if (OPENED == state) {
doSend();
sendThread.start();
private void send(String data) {
synchronized(sendQueue) {
sendQueue.add(data);
sendQueue.notifyAll();
* the main loop for the send thread
private void doSend() {
String msg = null;
while (OPENED == state && null != (msg = waitToSend())) {
try {
out.write(msg);
out.flush();
} catch(IOException e) {
e.printStackTrace();
setState(CLOSING);
close();
System.out.println("Thread="+Thread.currentThread().getName()+" ending");
* connect to a remote host
private void doConnect() {
try {
sock = new Socket(host, port);
name = ""+sock.getInetAddress()+":"+sock.getPort();
Thread.currentThread().setName("Send."+name);
in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
recvThread = new Thread(new Runnable() {
public void run() {
doRecv();
},"Recv."+name);
recvThread.start();
setState(OPENED);
} catch (IOException e) {
setState(CLOSED);
private void parseAddress(String txt) {
String ps = "";
int n = txt.indexOf(':');
          if(n == 0) {
               address = "127.0.0.1";
ps = txt.substring(1);
          } else if (n < 0) {
               address = txt;
               ps = "5050";
          } else {
               address = txt.substring(0,n);
               ps = txt.substring(n+1);
try {
port = Integer.parseInt(ps);
} catch(NumberFormatException e) {
port = 5050;
* get the connection name
public String getName(){return name;}
* the main loop for the receive thread
private void doRecv() {
String inbuf;
while (CLOSED != state) {
try {
inbuf = in.readLine();
} catch(Exception e) {
System.out.println(e);
inbuf = null;
if(inbuf == null) {
close();
} else {
postReceive(inbuf+"\r\n");
System.out.println("Thread="+Thread.currentThread().getName()+" ending");
private void close() {
if(state == OPENED) {
setState(CLOSING);
try {
sock.shutdownOutput();
} catch(IOException ie) {
ie.printStackTrace();
close();
} else if (state != CLOSED) {
try {
if (null != out) {
out.close();
if (null != in) {
in.close();
if (null != sock) {
sock.close();
}catch (Exception e) {
e.printStackTrace();
if (sendThread.isAlive()) {
sendThread.interrupt();
setState(CLOSED);
private String waitToSend() {
String msg = null;
synchronized(sendQueue) {
try {
while (sendQueue.isEmpty()) {
sendQueue.wait();
msg = (String)sendQueue.remove();
} catch (InterruptedException e) {
e.printStackTrace();
return msg;

Similar Messages

  • Simple socket connections

    Hey,
    I've been dabbling around with sockets lately, and I attempted to create a simple program that allows the client to send messages to the server. However, messages are not being either sent, or received (or both). I do know that the client IS detected and accepted by the server, and that the server is started properly on socket 9999. Here is the code I'm using:
    Client.java:
          public static void main(String [] args){
              Socket client = null;
              DataOutputStream output = null;
              DataInputStream input = null;
              Scanner clientInput = new Scanner(System.in);
              InetAddress address = null;
              try{
               address = InetAddress.getLocalHost();
              System.out.println(address);
              catch(UnknownHostException e){
                   System.out.println(e);
              try{
                   client = new Socket(address, 9999);
                   output = new DataOutputStream(client.getOutputStream());
                   input = new DataInputStream(client.getInputStream());
              catch(UnknownHostException e){
                   System.out.println("Cant find host");
              catch(IOException e){
                   System.out.println("IO Exception");
                   System.out.println(e);
         //     System.out.println("checkOne");
              if(client != null && output != null && input != null){
                   try{
                        boolean redo = true;
                        while(redo){
                             System.out.print("Send to server: ");
                             String text = clientInput.nextLine();
                             if(!(text.equals("!")))
                                  output.writeBytes(text);
                             else
                                  redo = false;
                             System.out.println();
                   catch(IOException e){
                        System.out.println(e);
              try{
              output.close();
              input.close();
              client.close();
              catch(Exception e){
                   System.out.println(e);
    Server.java:
         public static void main(String [] args){
              ServerSocket server = null;
              Socket client = null;
              DataInputStream input = null;
              PrintStream output = null;
              String line = "";
              try{
                   server = new ServerSocket(9999);
                   System.out.println("Server started on socket 9999");
              catch(Exception e){
                   System.out.println(e);
              try{
                   client = server.accept();
                   System.out.println("Client detected");
                   input = new DataInputStream(client.getInputStream());
                   output = new PrintStream(client.getOutputStream());
                   while(true){
                        line = input.readLine();
                        output.println(line);
              catch(Exception e){
                   System.out.println(e);
         }Could you please tell me what I did wrong with the above code? Did I forget to close a socket, send data incorrectly, or what?
    Thanks,
    Chris

    Chris.Y wrote:
    Client.java:
                             if(!(text.equals("!")))
                                  output.writeBytes(text);
                             else
    That might need to be something like
                             if(!(text.equals("!"))) {
                                  output.writeBytes(text);
                                  output.writeBytes("\015\012"); // append CR LF
                             elseto satisfy readLine() in the server.

  • Comunication question for socket server and socket client

    I created a simple socket server and a socket client
    The server receive request from server and send same request back to the client.
    Please see example code as below:
    package socket;
    import java.net.*;
    import java.io.*;
    public class SimpleServer {
    public SimpleServer(int listen_port) {
    this.listen_port = listen_port;
    public static void main(String[] args) {
    SimpleServer server = new SimpleServer(4444);
    server.acceptConnections();
    public void acceptConnections() {
    try {
    ServerSocket server = new ServerSocket(listen_port);
    Socket incomingConnection = null;
    while (true) {
    incomingConnection = server.accept();
    handleConnection(incomingConnection);
    } catch (BindException e) {
    System.out.println("Unable to bind to port " + listen_port);
    } catch (IOException e) {
    System.out.println("Unable to instantiate a ServerSocket on port: " + listen_port);
    public void handleConnection(Socket incomingConnection) {
    try {
    InputStream inputFromSocket = incomingConnection.getInputStream();
    BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputFromSocket));
    PrintWriter streamWriter = new PrintWriter(incomingConnection.getOutputStream());
    StringBuffer sb = new StringBuffer();
    String line = null;
    int i = 0;
    while((line=streamReader.readLine())!=null){
    streamWriter.println(line);
    break;
    streamWriter.close();
    streamReader.close();
    incomingConnection.close();
    } catch (Exception e) {
    protected int listen_port;
    //socket client
    package socket;
    import java.io.*;
    import java.net.*;
    import java.util.Iterator;
    import java.util.List;
    import java.math.*;
    public class Simple {
    public Simple(String host_ip, int host_port) {
    this.host_ip = host_ip;
    this.host_port = host_port;
    public static void main(String[] args) {
    Simple simple = new Simple("192.168.254.134", 4444);
    simple.setUpConnection();
    try {
    String result = simple.getResponse("This is first request");
    String result2 = simple.getResponse("This is second request");
    simple.tearDownConnection();
    catch (Exception e) {
    System.out.println("error");
    e.printStackTrace();
    public void setUpConnection() {
    try {
    // Create new socket object
    Socket client = new Socket(host_ip, host_port);
    socketReader = new BufferedReader(new InputStreamReader(client.
    getInputStream()));
    socketWriter = new PrintWriter(client.getOutputStream());
    } catch (UnknownHostException e) {
    System.out.println(
    "Error setting up socket connection: unknown host at " +
    host_ip + ":" + host_port);
    catch (IOException e) {
    System.out.println("Error setting up socket connection: " + e);
    public String getResponse(String request) {
    StringBuffer fileLines = new StringBuffer();
    try {
    socketWriter.println(request);
    socketWriter.flush();
    String line = null;
    int i = 0;
    int chars = 0;
    int sizeOfBuffer = 100;
    char[] cbuf = new char[sizeOfBuffer];
    while ( (chars = socketReader.read(cbuf)) >= 0) {
    fileLines.append(cbuf, 0, chars);
    } catch (Exception e) {
    e.printStackTrace();
    return fileLines.toString();
    public void tearDownConnection() {
    try {
    socketWriter.close();
    socketReader.close();
    } catch (IOException e) {
    System.out.println("Error tearing down socket connection: " + e);
    protected BufferedReader socketReader;
    protected PrintWriter socketWriter;
    protected String host_ip;
    protected int host_port;
    I send two request at the same time.
    Please see code in main method of Simple class
    String result = simple.getResponse("first");
    String result2 = simple.getResponse("second");
    What I think is the socket server will send the same request back to the client.
    So value of result and result2 should be 'first' and 'second'
    But it always return empty String for result2.
    What's the problem?
    Thanks for your help

    Your code has a couple of problems.
    1) the server doesn't flush its socket, so nothing will actually be sent until the socket is closed.
    2) the client getResponse() reads until end of file, so an attempt to use it a second time will fail
    3) in a real application the server should use threads. See the echo server I posted in http://forum.java.sun.com/thread.jsp?forum=11&thread=526980 reply 3.
    Also, please use the [code]  tags when posting source. The lack of these is probaly why you haven't had any repiles until now.

  • How to write a simple DB2 client?

    hello,
    I'm going to write a simple DB2 client in my new project,which can issue some simple db2 commands and get the result,for example,the "list tables" command. Can JDBC finish this job?
    any help appreciated.

    JDBC can do that and more.
    http://java.sun.com/docs/books/tutorial/jdbc/index.html
    %

  • Problem with Socket Client - Intermittent Truncated Response in AIX

    {color:#0000ff}Hi guru
    I have written on Socket Client method below to send request byte[] to Host and receive response byte[] from Host.
    For this particular response, I'm expecting Host to return me byte[] with length 2274.
    My problem is intermittently I received truncated message byte[] from Host with length only 1392. Sometimes I received full 2274 message, sometimes I received 1392 length. I tested in continual of 10 times by sending the same request to host, intermittently received truncated response message.
    My real problem is that this only happened in {color:#ff0000}AIX {color}machine. With the same class, I tested on {color:#ff0000}Windows {color}platform and i received full response message byte[] with 2274 lenght always. Therefore, im counting out the possibilities that Host might send me truncated message.
    Can anyone pls help to tell me how should I proceed to troubleshoot this problem in AIX? Is possible for me to trace what coming in?
    {color}
    public byte[] sendToHost(byte[] requestMessage, String requestId, String localTxnCode) throws Exception {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    long startTime = 0;
    long elapsed = 0;
    try {
    LogManager.log(LogManager.DEBUG, Constants.DEFAULT_LOGGER_NAME, requestId, "[" + localTxnCode + "] To connect and send message to Host hostAddr=[" + hostAddr + "], hostPort=[" + hostPort
    + "]");
    startTime = System.currentTimeMillis();
    hostSocket = new Socket(InetAddress.getByName(hostAddr), hostPort);
    hostSocket.setSoTimeout(timeOut);
    byte responseData[] = new byte[4096];
    bis = new BufferedInputStream(hostSocket.getInputStream());
    bos = new BufferedOutputStream(hostSocket.getOutputStream());
    bos.write(requestMessage);
    bos.flush();
    int length = bis.read(responseData);
    elapsed = System.currentTimeMillis() - startTime;
    ARBAdapterUtil.log(LogManager.DEBUG, Constants.DEFAULT_LOGGER_NAME, requestId, "[" + localTxnCode + "] Received message from Host length=[" + length + "]");
    // The response byte must not be 4096 everytime
    byte[] returnByte = new byte[length];
    for (int i = 0; i < length; i++) {
    returnByte[i] = responseData;
    return returnByte;
    } catch (BindException b) {
    elapsed = System.currentTimeMillis() - startTime;
    throw new SocketException("Socket Exception: BindException IP=" + hostAddr + " PORT=" + hostPort + " Error type=" + b.getClass().getName() + " Error message=" + b.getMessage());
    } catch (ConnectException c) {
    elapsed = System.currentTimeMillis() - startTime;
    throw new SocketException("Socket Exception: ConnectException IP=" + hostAddr + " PORT=" + hostPort + " Error type=" + c.getClass().getName() + " Error message=" + c.getMessage());
    } catch (NoRouteToHostException nrth) {
    elapsed = System.currentTimeMillis() - startTime;
    throw new SocketException("Socket Exception: NoRouteToHostException IP=" + hostAddr + " PORT=" + hostPort + " Error type=" + nrth.getClass().getName() + " Error message="+ nrth.getMessage());
    } catch (SocketTimeoutException se) {
    elapsed = System.currentTimeMillis() - startTime;
    throw new SocketTimeoutException("Socket Exception: SocketTimeoutException IP=" + hostAddr + " PORT=" + hostPort + " Error type=" + se.getClass().getName() + " Error message=" + se.getMessage());
    } catch (SocketException s) {
    elapsed = System.currentTimeMillis() - startTime;
    throw new SocketException("Socket Exception: SocketException IP=" + hostAddr + " PORT=" + hostPort + " Error type=" + s.getClass().getName() + " Error message=" + s.getMessage());
    } catch (Exception e) {
    elapsed = System.currentTimeMillis() - startTime;
    throw new Exception("Unknown Exception: Exception IP=" + hostAddr + " PORT=" + hostPort + "Error type=" + e.getClass().getName() + " Error message=" + e.getMessage());
    } finally {
    try {
    ARBAdapterUtil.log(LogManager.INFO, Constants.DEFAULT_LOGGER_NAME, requestId, "ARBConnection.sendToHost() [" + localTxnCode + "] Time Elapsed via Socket in millisecond = [" + elapsed + "]");
    if (bis != null) {
    bis.close();
    bis = null;
    if (bos != null) {
    bos.close();
    bos = null;
    } catch (Exception e) {
    LogManager.log(LogManager.ERROR, Constants.DEFAULT_LOGGER_NAME, requestId, "ARBConnection.sendToHost() [" + localTxnCode + "] Exception during closing BufferedInputStream and BufferedOutputStream");

    I tried to use DataInputStream.readFully(byte[]). However, I could not retrieve a single byte from Host. It won't return until it fills the buffer, or EOS occurs. Isn't that what you wanted?
    You need to believe it here. Either the sending application or Java or the sending TCP stack or the intervening routers or the receiving TCP stack or Java or the receiver can break up the transmission into 1 byte reads and there is nothing you can do about it at the receiver except what I said. BufferedInputStream will mask the effect to some extent but you still have to code under that assumption. You don't have any choice about this.

  • Unable to create a simple test client. Got ConfigException: JBO--33001

    I am trying to create a simple test client as per ADF training manual. Have just created an empty AM. The test client is giving this error at runtime.
    The test client looks like:
    public static void main(String args[])
    String amDef = "test.TestModule";
    String config = "TestModuleLocal";
    ApplicationModule am =
    Configuration.createRootApplicationModule(amDef, config);
    // Work with your appmodule and view object here
    Configuration.releaseRootApplicationModule(am, true);
    Getting the following error
    Exception in thread "main" oracle.jbo.ConfigException: JBO-33001: Cannot find the configuration file /test/common/bc4j.xcfg in the classpath
         at oracle.jbo.client.Configuration.loadFromClassPath(Configuration.java:432)
         at oracle.jbo.common.ampool.PoolMgr.createPool(PoolMgr.java:284)
         at oracle.jbo.common.ampool.PoolMgr.findPool(PoolMgr.java:539)
         at oracle.jbo.client.Configuration.createRootApplicationModule(Configuration.java:1252)
         at oracle.jbo.client.Configuration.createRootApplicationModule(Configuration.java:1230)
         at amit.bc4j.TestClient.main(TestClient.java:18)
    Process exited with exit code 1.
    I have added JAXB and Applications Core libraries to the default library list.
    (added JaxB because of http://myforums.oracle.com/jive3/thread.jspa?messageID=3425268&#3425268
    and Unable to create a simple test client. Error JAXBException
    I have checked that /home/aagupta/jdevhome/home/aagupta/jdevhome/FusionJdev/mywork/Test2/TestProj/classes/amit/bc4j/common/bc4j.xcfg file exists.
    I even tried to add this directory using Add lib/directory pane, but no help.
    Please suggest what to do...
    Thanks,
    Amit

    Got it....i paid the price of not understanding the error messages and expecting bc4jclient and ctrl+enter is a magic wand :)
    Thanks to Steinmeier,Oliver http://myforums.oracle.com/jive3/thread.jspa?messageID=3408700&#3408700
    The shortcut only generates sample code. We need to substitute the actual AM location.
    public static void main(String args[])
    String amDef = "amit.bc4j.model.TestAM";
    String config = "TestAMLocal";
    ApplicationModule am =
    Configuration.createRootApplicationModule(amDef, config);
    System.out.println("Read the messages!");
    // Work with your appmodule and view object here
    Configuration.releaseRootApplicationModule(am, true);
    }

  • Creating a simple java client for a session EJB local interface

    Hi all
    Is it possible to create a simple java client for a session ejb local interface with JDeveloper.
    The problem is that it creates a test client for a remote interface only...
    i.e.
    MySessionEJB sessionEJB = context.lookup("MySessionEJB")
    and once i try to adjust it manually for the local interface...
    MySessionEJBLocal sessionEJB = (MySessionEJBLocal) context.lookup("MySessionEJBLocal") (MySessionEJBLocal - is the name of my local interface)
    it generates the exception:
    javax.naming.NotFoundException: SessionEJBLocal not found
    at...........................(RMIClientContext.java:52)
    There is still no problem with accessing the local interface object from the jsf project where i've added <ejb-local-ref> tag into the web.xml file.
    but i need the possibility of testing the simple java client for the local interface to test business methods wich should return objects without indirect properties
    Thanks in advance.
    Alex.

    Pedja thanks for reply.
    I still dont understand what is wrong with my example.
    The first peace of the code i wrote (getting the reference to the remote interface object) works pretty well, and even more it is produced automatically by JDeveloper, so why we cant get a reference to the local interface object the same way?
    Certanly we should use the local interface for getting access to the resource functioning under the same local jvm and i think it doesnt metter wich app server we really use wls or oas or others
    Thanks. Alex.

  • Simple Socket Programming, But,.......

    This code is Server, Client Socket program code.
    Client send data to server and then, Server get data and save it
    to file in server.
    I think client works well.
    But, Server.java file have some problem.
    It generate ClassNotFoundException!
    So the result file have garbage value only.
    Any idea please................
    /////////////////////////// Server.java /////////////////////////////////
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Server extends JFrame
         private JTextField enter;
         private JTextArea display;
         ObjectInputStream input;
         ObjectOutputStream output;
         FileOutputStream resultFile;
         public Server(){
              super("Server");
              Container c = getContentPane();
              enter = new JTextField();
              enter.setEnabled(false);
              enter.addActionListener(
                   new ActionListener(){
                        public void actionPerformed(ActionEvent ev){
                             //None
              c.add(enter, BorderLayout.NORTH);
              display = new JTextArea();
              c.add(new JScrollPane(display),
                   BorderLayout.CENTER);
              setSize(300, 150);
              show();
         public void runServer(){
              ServerSocket server;
              Socket connection;
              int counter = 1;
              display.setText("");
              try{
                   server = new ServerSocket(8800, 100);
                   while(true){
                        display.append("Waiting for connection\n" + counter);
                        connection = server.accept();
                        display.append("Connection " + counter +
                             "received from: " + connection.getInetAddress().getHostName());
                        resultFile = new FileOutputStream("hi.txt");
                        output = new ObjectOutputStream(resultFile);
                        output.flush();
                        input = new ObjectInputStream(
                             connection.getInputStream()
                        display.append("\nGod I/O stream, I/O is opened\n");
                        enter.setEnabled(true);
                        DataForm01 data = null;
                        try{
                             data = (DataForm01) input.readObject();
                             output.writeObject(data);
                             data = (DataForm01) input.readObject();
                             output.writeObject(data);
                        catch(NullPointerException e){
                             display.append("Null pointer Exception");
                        catch(ClassNotFoundException cnfex){
                             display.append("\nUnknown Object type received");
                        catch(IOException e){
                             display.append("\nIOException Occured!");
                        if(resultFile != null){
                             resultFile.flush();
                             resultFile.close();
                        display.append("\nUser Terminate connection");
                        enter.setEnabled(false);
                        input.close();
                        output.close();
                        connection.close();
                        ++counter;
              catch(EOFException eof){
                   System.out.println("Client Terminate Connection");
              catch(IOException io){
                   io.printStackTrace();
              display.append("File is created!");
         public static void main(String[] args){
              Server app = new Server();
              app.addWindowListener(
                   new WindowAdapter(){
                        public void windowClosing(WindowEvent e){
                             System.exit(0);
              app.runServer();
    /////////////////////////// client.java /////////////////////////////////
    * Client.java
    * @author Created by Omnicore CodeGuide
    package Client;
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Client extends JFrame
         private JTextField enter;
         private JTextArea display;
         ObjectOutputStream output;
         String message = "";
         //DataForm01 dfrm[];
         public Client(){
              super("Client");
              Container c = getContentPane();
              enter = new JTextField();
              enter.setEnabled(false);
              enter.addActionListener(
                   new ActionListener(){
                        public void actionPerformed(ActionEvent e){
                             //None.
              c.add(enter, BorderLayout.NORTH);
              display = new JTextArea();
              c.add(new JScrollPane(display), BorderLayout.CENTER);
              setSize(300, 150);
              show();
         public void runClient(){
              Socket client;
              try{
                   display.setText("Attemption Connection...\n");
                   client = new Socket(InetAddress.getByName("127.0.0.1"), 8800);
                   display.append("Connected to : = " +
                        client.getInetAddress().getHostName());
                   output = new ObjectOutputStream(
                        client.getOutputStream()
                   output.flush();
                   display.append("\nGot I/O Stream, Stream is opened!\n");
                   enter.setEnabled(true);
                   dfrm = new DataForm01[10];
                   for(int i=0; i<10; i++){
                        dfrm[i] = new DataForm01();
                        dfrm.stn = i;
                        dfrm[i].name = "Jinbom" + Integer.toString(i);
                        dfrm[i].hobby = "Soccer" + Integer.toString(i);
                        dfrm[i].point = (double)i;
                   for(int i=0; i<10; i++){
                        try{
                             output.writeObject(dfrm[i]);
                             display.append(dfrm[i].getData());
                        catch(IOException ev){
                             display.append("\nClass is not founded!\n");
                   DataForm01 dfrm = new DataForm01();
                   dfrm.stn=1;
                   dfrm.name="Jinbom";
                   dfrm.hobby = "Soccer";
                   dfrm.point = (double)0.23;
                   DataForm01 dfrm02 = new DataForm01();
                   dfrm02.stn = 1;
                   dfrm02.name = "Jimbin";
                   dfrm02.hobby = "Soccer";
                   dfrm02.point = 0.4353;
                   try{
                        output.writeObject(dfrm);
                        display.append(dfrm.getData());
                        output.writeObject(dfrm02);
                        display.append(dfrm.getData());
                   catch(IOException ev){
                        display.append("\nClass is not founded!\n");
                   if(output != null) output.flush();
                   display.append("Closing connection.\n");
                   output.close();
                   client.close();
              catch(IOException ioe){
                   ioe.printStackTrace();
         public static void main(String[] args){
              Client app = new Client();
              app.addWindowListener(
                   new WindowAdapter(){
                        public void windowClosing(WindowEvent e){
                             System.exit(0);
              app.runClient();
    /////////////////////////// DataForm01.java /////////////////////////////////
    import java.io.*;
    public class DataForm01 implements Serializable
         int stn;
         String name;
         String hobby;
         double point;
         public String getData(){
              return Integer.toString(stn) + name + hobby + Double.toString(point);

    This is indented code. ^^;
    It's better to view.
    ////////////////////////// Server.java /////////////////////////////////////////
    * Server.java
    * @author Created by Omnicore CodeGuide
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Server extends JFrame
         private JTextField enter;
         private JTextArea display;
         ObjectInputStream input;
         ObjectOutputStream output;
         FileOutputStream resultFile;
         public Server(){
              super("Server");
              Container c = getContentPane();
              enter = new JTextField();
              enter.setEnabled(false);
              enter.addActionListener(
                   new ActionListener(){
                        public void actionPerformed(ActionEvent ev){
                             //None
              c.add(enter, BorderLayout.NORTH);
              display = new JTextArea();
              c.add(new JScrollPane(display),
                     BorderLayout.CENTER);
              setSize(300, 150);
              show();
         public void runServer(){
              ServerSocket server;
              Socket connection;
              int counter = 1;
              display.setText("");
              try{
                   server = new ServerSocket(8800, 100);
                   while(true){
                        display.append("Waiting for connection\n" + counter);
                        connection = server.accept();
                        display.append("Connection " + counter +
                             "received from: " + connection.getInetAddress().getHostName());
                        resultFile = new FileOutputStream("hi.txt");
                        output = new ObjectOutputStream(resultFile);
                        output.flush();
                        input = new ObjectInputStream(
                             connection.getInputStream()
                        display.append("\nGod I/O stream, I/O is opened\n");
                        enter.setEnabled(true);
                        DataForm01 data = null;
                        for(int i=0; i<10; i++){
                             try{
                                  data = (DataForm01) input.readObject();
                                  if(data == null) break;
                                  output.writeObject(data);
                             catch(NullPointerException e){
                                  display.append("Null pointer Exception");
                             catch(ClassNotFoundException cnfex){
                                  display.append("\nUnknown Object type received");
                             catch(IOException e){
                                  display.append("\nIOException Occured!");
                        DataForm01 data = null;
                        try{
                             data = (DataForm01) input.readObject();
                             output.writeObject(data);
                             data = (DataForm01) input.readObject();
                             output.writeObject(data);
                        catch(NullPointerException e){
                             display.append("Null pointer Exception");
                        catch(ClassNotFoundException cnfex){
                             display.append("\nUnknown Object type received");
                        catch(IOException e){
                             display.append("\nIOException Occured!");
                        if(resultFile != null){
                             resultFile.flush();
                             resultFile.close();
                        display.append("\nUser Terminate connection");
                        enter.setEnabled(false);
                        input.close();
                        output.close();
                        connection.close();
                        ++counter;
              catch(EOFException eof){
                   System.out.println("Client Terminate Connection");
              catch(IOException io){
                   io.printStackTrace();
              display.append("File is created!");
         public static void main(String[] args){
              Server app = new Server();
              app.addWindowListener(
                   new WindowAdapter(){
                        public void windowClosing(WindowEvent e){
                             System.exit(0);
              app.runServer();
    ////////////////////////// Client.java /////////////////////////////////////////
    * Client.java
    * @author Created by Omnicore CodeGuide
    package Client;
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Client extends JFrame
         private JTextField enter;
         private JTextArea display;
         ObjectOutputStream output;
         String message = "";
         //DataForm01 dfrm[];
         public Client(){
              super("Client");
              Container c = getContentPane();
              enter = new JTextField();
              enter.setEnabled(false);
              enter.addActionListener(
                   new ActionListener(){
                        public void actionPerformed(ActionEvent e){
                             //None.
              c.add(enter, BorderLayout.NORTH);
              display = new JTextArea();
              c.add(new JScrollPane(display), BorderLayout.CENTER);
              setSize(300, 150);
              show();
         public void runClient(){
              Socket client;
              try{
                   display.setText("Attemption Connection...\n");
                   client = new Socket(InetAddress.getByName("127.0.0.1"), 8800);
                   display.append("Connected to : = " +
                          client.getInetAddress().getHostName());
                   output = new ObjectOutputStream(
                        client.getOutputStream()
                   output.flush();
                   display.append("\nGot I/O Stream, Stream is opened!\n");
                   enter.setEnabled(true);
                   dfrm = new DataForm01[10];
                   for(int i=0; i<10; i++){
                        dfrm[i] = new DataForm01();
                        dfrm.stn = i;
                        dfrm[i].name = "Jinbom" + Integer.toString(i);
                        dfrm[i].hobby = "Soccer" + Integer.toString(i);
                        dfrm[i].point = (double)i;
                   for(int i=0; i<10; i++){
                        try{
                             output.writeObject(dfrm[i]);
                             display.append(dfrm[i].getData());
                        catch(IOException ev){
                             display.append("\nClass is not founded!\n");
                   DataForm01 dfrm = new DataForm01();
                   dfrm.stn=1;
                   dfrm.name="Jinbom";
                   dfrm.hobby = "Soccer";
                   dfrm.point = (double)0.23;
                   DataForm01 dfrm02 = new DataForm01();
                   dfrm02.stn = 1;
                   dfrm02.name = "Jimbin";
                   dfrm02.hobby = "Soccer";
                   dfrm02.point = 0.4353;
                   try{
                        output.writeObject(dfrm);
                        display.append(dfrm.getData());
                        output.writeObject(dfrm02);
                        display.append(dfrm.getData());
                   catch(IOException ev){
                        display.append("\nClass is not founded!\n");
                   if(output != null) output.flush();
                   display.append("Closing connection.\n");
                   output.close();
                   client.close();
              catch(IOException ioe){
                   ioe.printStackTrace();
         public static void main(String[] args){
              Client app = new Client();
              app.addWindowListener(
                   new WindowAdapter(){
                        public void windowClosing(WindowEvent e){
                             System.exit(0);
              app.runClient();
    ////////////////////////// DataForm01.java /////////////////////////////////////////
    * DataForm01.java
    * @author Created by Omnicore CodeGuide
    import java.io.*;
    public class DataForm01 implements Serializable
         int stn;
         String name;
         String hobby;
         double point;
         public String getData(){
              return Integer.toString(stn) + name + hobby + Double.toString(point);

  • Simple Chat Client using Java

    Hi again. I'm thring to implement a simple chat client into my game and I need some help coding it, because it's way over my head. lol thanks

    Well, you have left your question very vague, and people tend to get irritated by it. First of all, you need to really specify what you need. If you have nothing and need everything....you need to start by thinking about what methods will be used to send the messages...the GUI should be the last part. Do you need a server, plan on using a public server, or in a LAN environment. If you need a server, what type? Do you plan on writing your own?
    For example, if you wanted to use an IRC server as your server, you could use PircBot as your backend for the communication and then integrate that into a GUI. If you wanted AOL, there are packages out there you can use.
    If you have things thought out, you need to tell us what you are really asking and what you aready have. Otherwise, you have a lot of things to think about.

  • ## A Simple VB Client which passes a String as parameter ##

    Hello Everybody,
    I am looking for a simple VB client that should be able to pass a String
    (not FML) to a tuxedo service. I have already seen the FML example. Help
    would be highly appreciated.
    Thank you
    Nadeem
    @8563

    Hello,
    Please refer to my posting "Re: VB6 client and Tuxedo".
    The sample can be easily modified for STRING instead of FML.
    HTH
    regards
    MS

  • Please tell me how to use the Simple bluetooth client server example.

    Hi i used the simple bluetooth client server example in labview 7.1. Iam getting an error saying your system does not support the network operation.  I have following doubts also.
    1. Should i pair the device before running the labview.
    2. Should i enable the file transfer wizard in the software given with the bluetooth adapter.
    Please help
    Thank you
    R.Prem kumar 
    09940446193

    Hi R.Prem,
    Could you please let me know what error code is associated with this error message? Also could you please provide a description of the setup you are currently using? Thanks!
    Best regards,
    Steven

  • Can Simple Data Client/Server VIs communicate between computers?

    I am having trouble using the Simple Data Client VI / Simple Data Server VI to communicate between computers? Can these VIs do this ..or do they simply communicate between each other on a single computer? TIA.

    NO it can be used between two computers. You have to replace the localhist string with the IP address of the computer running the server and make sure that the server computer is allowing external connections on the specified port.
    Regards,
    André
    Using whatever version of LV the customer requires. (LV5.1-LV2012) (www.carya.nl)

  • How to design socket client-server app for 2-way communication

    Hi, I am writing a client-server application. I have a single server and many clients. Each client will need the ability to send information to the server at any time. The server will also need the ability to send information to a client at any time. Its this second part that I am not sure how to design. Would I need to create a SocketServer on each client to accept incoming messages, or is there a better way? Thanks

    scranchdaddy wrote:
    Don't my requirements sound a lot like an IM application, where a chat server might need to send a message to a chat client at any time?Not really. If that is what you are designing
    in my opinion one could easily be forgiven for thinking you were deliberately obfuscating your goal...
    How does the server know where the client is? Does it know the IP address of the client?I would imagine the server would contain a directory of IPs? I'm not sure.
    What happens if the client is not running?Then I guess the message would not get delivered.
    What happens if the client is behind a firewall that does not allow incoming connections?How do IM chat clients work? How have people solved this in the past?Typically the server would only care about clients currently connected to the server.
    Maybe you should re-think your design. I don't really have a design, just requirements, that's why I'm writing this post.Your subject says "+How to *design* socket client-server app for 2-way communication+".
    Are you saying you expect someone else to do the design for you?

  • Need help regarding Simple Data Client and Simple Data Server VIs

    Hi everyone.
    I have a simple objective. I just want to test the 2 example VIs, "Simple Data Client" and "Simple Data Server" between 2 computers. I just want to check whether is this working between the 2 computers.
    What I have done for now is that I changed the "address", from "localhost" in the "Simple Data Client.vi" to the IP address of the computer running the "Simple Data Server". I runned the "Simple Data Server" VI in one of the computers first followed by the "Simple Data Client" in the other computer. Nothing is received and the client just timed out.
    Can anyone please help me troubleshoot and tell me what are the possible problems for this? Are there any wires connections between 2 computers that I am missing or any other configurations I have to make before I can successfully do this?
    Thanks.
    Regards,
    Jonathan

    Hi Lee.P.
    I understand that. I was just feeling frustrated about the project not working. Sincere apologies from me.
    I was wrong about the error number. It is not Error 60. It is Error 59 - The network is down, unreachable, or has been reset.. Yes, I have tried changing the port numbers at the 2 computers when trying to send/receive.
    Could anything else be the problem?
    Regards,
    Jonathan  

  • Simple server/client socket in applets code.

    Can anyone please help me with Java sockets ? I want to create an applet that simply checks if it's still online. This means that i'll be using this applet thru modem(that is, dial-up connection). All i want the applet to do is send a signal to the server and the server answer back that it is still online. The server should be able to handle multiple sends and receives. I need just a simple code for me to work on (both server and client). The client doesn't have to send any special message to the server and vice versa.
    Thanks.

    Below is the code for both Applet and Servlet .I think this will solve your problem.
    Applet:
    import java.applet.*;
    import java.awt.*;
    import java.io.*;
    import java.net.*;
    public class OnlineApplet extends Applet implements Runnable
         private static Thread thread;
         private static HttpURLConnection URLConn;
         public void init()
              try
                   //Connect to the URL where servlet is running.
                   URL url = new URL("http://localhost/servlet/OnlineServlet");
                   URLConn = (HttpURLConnection)url.openConnection();
                   URLConn.setDoInput(false);
                   URLConn.setDoOutput(true);
              catch (Exception ex)
              thread = new Thread(this);
         public void start()
              thread.start();
         public void paint(Graphics g) {}
         public void stop() { }
         public void destroy() { }
         public void run()
              while(true)
                   try
                        thread.sleep(1000 * 60);
                        sendConfirmation();
                   catch (Exception ex)
         private void sendConfirmation() throws Exception
              DataOutputStream dos = new DataOutputStream(URLConn.getOutputStream());
              dos.writeChars("Fine");
              dos.flush();
              dos.close();
    Servlet:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    public class OnlineServlet extends HttpServlet implements Runnable
         public static Hashtable hsh;
         private static Thread thread;
         public void init(ServletConfig scon) throws ServletException
              hsh = new Hashtable();
              thread = new Thread(this);
         public void service(HttpServletRequest req, HttpServletResponse res)
              String strHostName = req.getRemoteHost();
              if(hsh.containsKey(strHostName))
                   updateHash(strHostName);
              else
                   hsh.put(strHostName, System.currentTimeMillis() + "");
         private void updateHash(String strHostName)
              hsh.remove(strHostName);
              hsh.put(strHostName, System.currentTimeMillis() + "");
         public void run()
              while(true)
                   try
                        thread.sleep(1000 * 120);
                   catch (Exception ex)
                   validateUsers(System.currentTimeMillis());
         private void validateUsers(long msec)
              Enumeration keys = hsh.keys();
              int size = hsh.size();
              while(keys.hasMoreElements())
                   String strKey = keys.nextElement().toString();
                   String strLong = hsh.get(strKey).toString();
                   long lg1 = Long.parseLong(strLong);
                   if((lg1 - msec) > 100000)
                        // This means there is no response from user . That means he is not online. So you can remove from hashtable.
                        hsh.remove(strKey);

Maybe you are looking for