Close Client

how to close client to dont get
java.net.SocketException: Connection reseti dont know why Telnet conection is ok
I know that i close socket i wrong order but how to do
this properly

CLIENT
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
public class Klient2 extends JFrame implements Runnable,ActionListener,WindowListener{
     JTextField wyss;
     JScrollPane scrollPane2;
     JList listaUSER;
     JLabel l1;
     Socket gniazdo;
     Thread w;
     DataInputStream in;
     DataOutputStream out;
     Convert convert = new Convert();
     JButton b1,b2,b3;
     String login;
     byte [] buffor = new byte [200];
     boolean l = true,petla = true;
     public  Klient2(){
          this.addWindowListener(this);
          this.setLayout(null);
          this.setSize(500,400);
          wyss = new JTextField();
          wyss.setSize(160,30);
          wyss.setLocation(80,140);
          this.add(wyss);
          b1 = new JButton("Wyslij");
          b1.setBounds(220,250,80,30);
          b1.addActionListener(this);
          b1.setActionCommand("wyslij");
          b1.setVisible(false);
          this.add(b1);
          b2 = new JButton("login");
          b2.setBounds(250,140,80,30);
          b2.addActionListener(this);
          b2.setActionCommand("login");
          this.add(b2);
          l1 = new  JLabel();
          l1.setBounds(180,220,100,30);
          this.add(l1);
          b3 = new JButton("exit");
          b3.setBounds(220,300,80,30);
          b3.addActionListener(this);
          b3.setActionCommand("exit");
          b3.setVisible(false);
          this.add(b3);
          listaUSER = new JList();
          //listaUSER.addMouseListener(this);
          scrollPane2 = new JScrollPane(listaUSER,
                    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
          scrollPane2.setSize(120,200);
          scrollPane2.setLocation(240, 20);
          scrollPane2.setVisible(false);
          this.add(scrollPane2);
     public void actionPerformed(ActionEvent e) {
          if(e.getActionCommand().equals("exit")){
               try {
                    petla = false;
                    //gniazdo.close();
                    out.close();
                    in.close();
                    l = true;
                    System.exit(0);
               } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
          if(e.getActionCommand().equals("login")){
               if(l == true){
               try {
                    gniazdo = new Socket("127.0.0.1",2347);
               } catch (UnknownHostException e1) {
                    e1.printStackTrace();
               } catch (IOException e1) {
                    e1.printStackTrace();
                              w = new Thread(this);
                              w.start();
                              l = false;
                              try {
                                   out = new DataOutputStream( gniazdo.getOutputStream());
                              } catch (IOException e1) {
                                   // TODO Auto-generated catch block
                                   e1.printStackTrace();
                         String header = "L1";
                         String text = wyss.getText();
                         byte [] headerByte = header.getBytes();
                         byte [] loginByte = text.getBytes();
                         int loginSize = loginByte.length;
                         byte [] loginSizeByte =convert.int2bytearray(loginSize);
                         byte [] sendLogin = new byte [2+4+loginSize];
                         for(int i=0;i<2;i++){
                              sendLogin[i] = headerByte;
                         for(int i=2,j=0;i<6;i++,j++){
                              sendLogin[i] = loginSizeByte[j];
                         for(int i=6,j=0;i<sendLogin.length;i++,j++){
                              sendLogin[i] = loginByte[j];
                              try {
                                   out.write(sendLogin);
                                   out.flush();
                              } catch (IOException e1) {
                                   // TODO Auto-generated catch block
                                   e1.printStackTrace();
     public void run() {
          while(petla){
               try {
                    in = new DataInputStream( gniazdo.getInputStream());
                    out = new DataOutputStream( gniazdo.getOutputStream());
                    in.read(buffor);
                    byte [] headerByte = new byte [2];
                    for(int i=0;i<2;i++){
                         headerByte[i] = buffor[i];
                    String hader = new String(headerByte);
                    System.out.println(hader);
                    if(hader.equals("LO")){
                         scrollPane2.setVisible(true);
                         wyss.setVisible(false);
                         b2.setVisible(false);
                         b3.setVisible(true);
                         l1.setText("");
                         byte [] listaSizeByte = new byte [4];
                         for(int i=2,j=0;i<6;i++,j++){
                              listaSizeByte[j] = buffor[i];
                         int listaSize = convert.bytearray2int(listaSizeByte);
                         System.out.println(listaSize);
                         byte [] listaByte = new byte [listaSize ];
                         for(int i=6, j=0 ; i < 6 + listaByte.length ; i++ ,j++){
                              listaByte[j] = buffor[i];
                         String listaIN = new String(listaByte);
                         System.out.println(listaIN);
                         String lis [] = listaIN.split("#");
                         listaUSER.setListData(lis);
                    }else if(hader.equals("LN")){
                         l1.setText("login zajety");
               } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
               break;
     public void windowOpened(WindowEvent arg0) {
          // TODO Auto-generated method stub
     public void windowClosing(WindowEvent e) {
          System.out.println("ZAMYKAM");
          try {
               petla = false;
               if(l == false){
               out.close();
               in.close();
          } catch (IOException e1) {
               // TODO Auto-generated catch block
               e1.printStackTrace();
     public void windowClosed(WindowEvent arg0) {
     public void windowIconified(WindowEvent arg0) {
          // TODO Auto-generated method stub
     public void windowDeiconified(WindowEvent arg0) {
          // TODO Auto-generated method stub
     public void windowActivated(WindowEvent arg0) {
          // TODO Auto-generated method stub
     public void windowDeactivated(WindowEvent arg0) {
          // TODO Auto-generated method stub
     public static void main(String[] args) {
          Klient2 frmae = new Klient2();
          frmae.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frmae.setSize(400,400);
          frmae.setLocation(10,10);
          frmae.setVisible(true);
SERVER
import java.net.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.*;
public class Serwer2 extends Thread {
     public final static int defaultPort = 2347;
     ServerSocket theServer;
     Socket s;
     static int numberOfThreads = 2;
     String headerOUT,listOUT="",loginString ;
     byte [] buffor = new byte [200];
     byte [] outByte;
     byte [] headerByte = new byte[2];
     byte [] loginSize = new byte[4];
     serwerGUI2 GUI;
     Convert convert = new Convert();
     ArrayList userList = new ArrayList();
     ArrayList socketList = new ArrayList();
     HashMap mapa = new HashMap();
     public Serwer2(serwerGUI2 gui,ServerSocket ss,ArrayList l ,ArrayList ll,HashMap lll ){
          this.GUI =gui;
          this.theServer = ss;
          this.userList = l;
          this.socketList =ll;
          this.mapa =lll;
     public void run() {
          GUI.pole.append("Uruchomiono watek nasluchujacy"+Thread.currentThread().getName()+"\n");
          while (true) {
               GUI.pole.append("Watek "+Thread.currentThread().getName()+"oczekuje polaczen\n");
               try {
                    s = theServer.accept();
                    socketList.add(s);
                    DataOutputStream out = new  DataOutputStream(s.getOutputStream());
                    DataInputStream in = new  DataInputStream(s.getInputStream());
                    while (true) {
                         int n = in.read(buffor);
                         if (n == -1)
                              socketList.remove(s);
                              userList.remove(loginString);
                              mapa.remove(loginString);
                              headerOUT = "LO";
                              listOUT  ="";
                              for(int i=0;i<userList.size();i++){
                                   listOUT += (String)userList.get(i)+"#";
                              byte [] outheader = headerOUT.getBytes();
                              byte [] listaByte = listOUT.getBytes();
                              int listSize = listaByte.length;
                              byte [] listSizeByte = convert.int2bytearray(listSize);
                              byte [] outLista = new byte [2+4+listSize];
                              for(int i=0;i<2;i++){
                                   outLista[i] =outheader;
                              for(int i=2,j=0;i<6;i++,j++){
                                   outLista[i] =listSizeByte[j];
                              for(int i=6,j=0;i<outLista.length;i++,j++){
                                   outLista[i] =listaByte[j];
                              for(int i=0; i < socketList.size() ;i++){
                                   DataOutputStream out1 = new DataOutputStream(((Socket)socketList.get(i)).getOutputStream());
                                   out1.write(outLista);
                                   out1.flush();
                              GUI.pole.append("Zakonczono polaczenie dlawatku "+Thread.currentThread().getName()+"\n");
                              break;
                         outByte = new byte[n];
                         for(int i = 0 ;i<2;i++){
                              headerByte[i] = buffor[i];
                         String header = new String(headerByte);
                         if(header.equals("L1")){
                              for(int i = 2, j = 0 ;i < 6; i++ ,j++){
                                   loginSize[j] = buffor[i];
                         int size = convert.bytearray2int(loginSize);
                         byte [] loginByte = new byte[size];
                              for(int i = 6, j = 0 ;i < 6+size; i++ ,j++){
                                   loginByte[j] = buffor[i];
                         loginString = new String(loginByte);
                         int przed =mapa.size();
                         mapa.put(loginString,s);
                         int po = mapa.size();
                         if(przed == po){
                              headerOUT = "LN";
                              out.write(headerOUT.getBytes());
                              out.flush();
                         }else{
                              headerOUT = "LO";
                              userList.add(loginString);
                              listOUT = "";
                              for(int i=0;i<userList.size();i++){
                                   listOUT += (String)userList.get(i)+"#";
                              byte [] outheader = headerOUT.getBytes();
                              byte [] listaByte = listOUT.getBytes();
                              int listSize = listaByte.length;
                              byte [] listSizeByte = convert.int2bytearray(listSize);
                              byte [] outLista = new byte [2+4+listSize];
                              for(int i=0;i<2;i++){
                                   outLista[i] =outheader[i];
                              for(int i=2,j=0;i<6;i++,j++){
                                   outLista[i] =listSizeByte[j];
                              for(int i=6,j=0;i<outLista.length;i++,j++){
                                   outLista[i] =listaByte[j];
                              for(int i=0; i < socketList.size() ;i++){
                                   DataOutputStream out1 = new DataOutputStream(((Socket)socketList.get(i)).getOutputStream());
                                   out1.write(outLista);
                                   out1.flush();
                         /*out.write(headerOUT.getBytes());
                         out.flush();*/
                         GUI.pole.append(loginString+"\n");     
                    } // end while
               } // end try
               catch (IOException ex) {
          } // end while
     } // end run
SERVER GUI
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.util.*;
public class serwerGUI2 extends JFrame implements ActionListener{
     JButton b1;
     public  JTextArea pole;
     JScrollPane skrol;
     //Klient_pula p;
     ServerSocket theServer;
     Socket s;
     static int numberOfThreads = 3;
     BufferedReader in;
     PrintStream out,outall;
     ArrayList lista;
     public serwerGUI2(){
          super("serwer");
          this.setLayout(null);
          b1 = new JButton("polocz");
          b1.setSize(100,30);
          b1.setLocation(10,10);
          b1.addActionListener(this);
          this.add(b1);
          pole = new JTextArea();
          skrol = new JScrollPane(pole,
                    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
          skrol.setSize(200,200);
          skrol.setLocation(150,10);
          this.add(skrol);
     public static void main(String[] args) {
          serwerGUI2 frmae = new serwerGUI2();
          frmae.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frmae.setSize(400,400);
          frmae.setLocation(10,10);
          frmae.setVisible(true);
     public void actionPerformed(ActionEvent e) {
          if(e.getActionCommand().equals("polocz")){
               try {
                    pole.append("Serwer zostal uruchomiony na porcie 2347 \n");
                    ServerSocket ss = new ServerSocket(2347);
                    ArrayList l = new ArrayList();
                    ArrayList ll = new ArrayList();
                    HashMap mapa = new HashMap();
                    //l[0] =;
                    for (int i = 0; i < numberOfThreads; i++) {
                         Serwer2 pes = new Serwer2(this,ss,l,ll,mapa);
                         pes.start();
                         //pes.w.start();
               catch (IOException ex) { System.err.println(ex); }
Convert
import java.nio.ByteBuffer;
public class Convert {
     public static byte[] int2bytearray(int i) {
            byte b[] = new byte[4];
            ByteBuffer buf = ByteBuffer.wrap(b);
            buf.putInt(i);
            return b;
          public static int bytearray2int(byte[] b) {
            ByteBuffer buf = ByteBuffer.wrap(b);
            return buf.getInt();

Similar Messages

  • FU Ant task failure: java.util.concurrent.ExecutionException: could not close client/server socket

    We sometimes see this failure intermitently when using the FlexUnit Ant task to run tests in a CI environment. The Ant task throws this exception:
    java.util.concurrent.ExecutionException: could not close client/server socket
    I have seen this for a while now, and still see it with the latest 4.1 RC versions.
    Here is the console output seen along with the above exception:
    FlexUnit player target: flash
    Validating task attributes ...
    Generating default values ...
    Using default working dir [C:\DJTE\commons.formatter_swc\d3flxcmn32\extracted\Source\Flex]
    Using the following settings for the test run:
    FLEX_HOME: [C:\dev\vert-d3flxcmn32\302100.41.0.20110323122739_d3flxcmn32]
    haltonfailure: [false]
    headless: [false]
    display: [99]
    localTrusted: [true]
    player: [flash]
    port: [1024]
    swf: [C:\DJTE\commons.formatter_swc\d3flxcmn32\extracted\build\commons.formatter.tests.unit.sw f]
    timeout: [1800000ms]
    toDir: [C:\DJTE\commons.formatter_swc\d3flxcmn32\reports\xml]
    Setting up server process ...
    Entry  [C:\DJTE\commons.formatter_swc\d3flxcmn32\extracted\build] already  available in local trust file at  [C:\Users\user\AppData\Roaming\Macromedia\Flash  Player\#Security\FlashPlayerTrust\flexUnit.cfg].
    Executing 'rundll32' with arguments:
    'url.dll,FileProtocolHandler'
    'C:\DJTE\commons.formatter_swc\d3flxcmn32\extracted\build\commons.formatter.tests.unit.swf '
    The ' characters around the executable and arguments are
    not part of the command.
    Starting server ...
    Opening server socket on port [1024].
    Waiting for client connection ...
    Client connected.
    Setting inbound buffer size to [262144] bytes.
    Receiving data ...
    Sending acknowledgement to player to start sending test data ...
    Stopping server ...
    End of test data reached, sending acknowledgement to player ...
    When the problem occurs, it is not always during the running of any particular test (that I am aware of). Recent runs where this failure was seen had the following number of tests executed (note: the total number that should be run is 45677): 18021, 18, 229.
    Here is a "good" run when the problem does not occur:
    Setting inbound buffer size to [262144] bytes.
    Receiving data ...
    Sending acknowledgement to player to start sending test data ...
    Stopping server ...
    End of test data reached, sending acknowledgement to player ...
    Closing client connection ...
    Closing server on port [1024] ...
    Analyzing reports ...
    Suite: com.formatters.help.TestGeographicSiteUrls
    Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 sec
    Suite: com.formatters.functionalUnitTest.testCases.TestNumericUDF
    Tests run: 13, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.071 sec
    Results :
    Tests run: 45,677, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 201.186 sec
    Has anyone else ran across this problem?
    Thanks,
    Trevor

    I am not sure if this information will help everyone, but here goes...
    For us, these problems with FlexUnit tests crashing the Flash Player appear to be related to couple of factors. Recently, we moved up from Flex 3.2 to Flex 4.1 as our development baseline.  Many people complained that their development environment (Flash Builder, etc.) was much more unstable.  Apparently, 4.1 produces SWFs that require more memory to run than 3.2 does?  Anyway, we still had Flash Player 10.1 as our runtime baseline.  Apparently, that version of the player was not as capable of running larger FlexUnit test SWFs, and would crash (as I posted months earlier).  I upgraded to the latest 10.3 standalone player versions, and the crashes have now ceased.  It would be nice to know exactly what was causing the crashes, but memory management (or lack of) is my best guess.
    So, if you are seeing these issues, try upgrading to the latest Flash Player version.
    Regards,
    Trevor

  • How to proxy messages from client?

    Hello, i have a problem on how am i gonna proxy the messages from a sender client, to be sent to it's requested client recipient...
    clientA(want talk to clientB) --> server(sent to clientB) --> clientB(receive)
    and of course vice versa.. what should i do...
    server..
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Strider extends JFrame implements ActionListener {
      JButton sendbutton;
      JTextField txtfield;
      JTextArea txtarea;
      ObjectOutputStream output;
      ObjectInputStream input;
      private int counter = 1;
      ServerSocket server;
      Socket connection;
      ThreadHandler client;
      public Strider() {
        super("Server Strider Running: No# of Client Connected: ");
        Container c = getContentPane();
        c.setLayout(new FlowLayout());
        JButton sendbutton = new JButton("&SEND");
        JTextField txtfield = new JTextField(10);
        JTextArea txtarea = new JTextArea(10, 20);
        sendbutton.addActionListener(this);
        txtfield.addActionListener(this);
        txtfield.setEnabled(true);
        txtarea.setEnabled(false);
        c.add(sendbutton);
        c.add(txtfield);
        c.add(new JScrollPane(txtarea));
        setSize(230, 250);
        show();
      public void runStrider() {
        try {
         server = new ServerSocket(5000, 100);
        catch(IOException e) {
          e.printStackTrace();
          System.exit(1);
        try{
         do {
           ThreadHandler clientThread = new ThreadHandler(server.accept(), this);     
            //txtarea.append("Connection " + counter + "received from: " + clientThread.connection.getInetAddress().getHostName());
           //txtarea.append("\nGot I/O Stream!");
           clientThread.start();       
            ++counter;
         }while(true);
        catch(IOException e) {
         e.printStackTrace();
         System.exit(1);
      public void actionPerformed(ActionEvent e) {
       if (e.getSource() == sendbutton)
          sendData(txtfield.getText());
       else
          sendData(e.getActionCommand());
      public void sendData(String msg) {
       try {
         clientThread.output.writeObject("Strider>> " + msg);
         clientThread.output.flush();
         txtarea.append("\nStrider>> " + msg);
       catch(IOException io) {
         txtarea.append("\nError Writing Object");
      public void update(String message) {
           String msg = null;
           msg = message;
           //txtarea.setText(msg);
          //txtarea.setCaretPosition(txtarea.getText().length());
      public static void main(String[] args) {
        Strider app = new Strider();
        app.addWindowListener(
          new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
              System.exit(0);
        app.runStrider();
      class ThreadHandler extends Thread{
        private Socket connection;
        protected ObjectOutputStream output;
        protected ObjectInputStream input;
         Strider str;
        String message = " ";
        int count = 0;
        public ThreadHandler(Socket s, Strider x) {
         connection = s;
         str = x;
        public void run() {
         String msg = null;
         try {
          output = new ObjectOutputStream(connection.getOutputStream());
          output.flush();
          input = new ObjectInputStream(connection.getInputStream());
          //message  = "Connection received";
             //str.update(message); //+ connection.getInetAddress().getHostName());
          //message = "\nGot I/O Stream!";
          //str.update(message);
          //txtfield.setEnabled(false);
          message = "Strider>> Connection Succesful! \nWelcome to Cybersoft's Underground Community :)";
          output.writeObject(message);
          output.flush();
          //txtfield.setText(" ");
            do {
              msg += (String) input.readObject();
                ++count;
                if(count == counter)
                     output.writeObject(msg);
                //str.update(msg);
            }while(!message.equals("Client>>Terminate"));
          input.close();
           output.close();
          connection.close();
           ++counter;
         catch(IOException e) {
          e.printStackTrace();
          catch(ClassNotFoundException cnfx) {
           cnfx.printStackTrace();
    }client...
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Hiryu extends JFrame implements ActionListener
      ObjectOutputStream output;
      ObjectInputStream input;
      String msg;
      JTextField txtfld1, txtfld2;
      JPanel txtpanel;
      JTextArea txtarea;
      public Hiryu()
         Container c = getContentPane();
         c.setLayout(new BorderLayout());
         txtfld1 = new JTextField(10);
         txtfld2 = new JTextField(10);
         txtarea = new JTextArea(10,20);
         txtpanel = new JPanel();
         txtpanel.setLayout(new GridLayout(2, 1));
         txtfld1.addActionListener(this);
         txtfld2.addActionListener(this);    
         txtpanel.add(txtfld1);
         txtpanel.add(txtfld2);
         c.add(txtpanel, BorderLayout.NORTH);
         c.add(new JScrollPane(txtarea), BorderLayout.CENTER);
         setSize(230,250);
         show();
      public void actionPerformed(ActionEvent e)
         if (e.getSource() == txtfld1)
           sendData(e.getActionCommand());
         //else
           //runClient();
      public void runClient()
         Socket client;
         String s = txtfld2.getText();
         try {
          txtarea.setText("Attempting Connection\n");
          client = new Socket(InetAddress.getByName("192.168.2.109"), 5000);
          txtarea.append("Connected to:" + client.getInetAddress().getHostName());
           output = new ObjectOutputStream(client.getOutputStream());
           output.flush();
           input = new ObjectInputStream(client.getInputStream());
           txtarea.append("\n Got I/O Streams \n");
           msg = "Client>> Connection Successful";
           output.writeObject(msg);
           output.flush();
           do{
            try{
              msg = (String) input.readObject();
              txtarea.append("\n" + msg);
              txtarea.setCaretPosition(txtarea.getText().length());
            catch(ClassNotFoundException cnfex){
             txtarea.append("\nUnknown Object type received");
           }while(!msg.equals("Server>> Terminate"));
           txtarea.append("\nUser Terminated connection");
           output.close();
           input.close();
           client.close();
           //++counter;
         catch(EOFException eof){
          System.out.println("Client terminated connection");
         catch(IOException io){
          io.printStackTrace();
      public void sendData(String s)
         try{
          output.writeObject("Client>>" + s);
          output.flush();
          txtarea.append("\nClient>>" + s);
         catch(IOException cnfex){
          txtarea.append("\nError writing Object");
      public static void main(String[] args)
         Hiryu app = new Hiryu();
         app.addWindowListener(
          new WindowAdapter()
             public void windowClosing(WindowEvent e)
                System.exit(0);
         app.runClient();
    }

    Though you can initiate the binary from your client side but for the file creation, there is no other way but to store it on the server side. So your best bet would be to get some space free on the server side of yours.
    Aman....

  • How to send a message from server to a particular client

    Hi all,
    I need to send a message from one host to another host which are connected in local domain. Now I'm able to send a message from client to server and vice versa but what I need is the server should route that message which I send through one client to another host(client) .
    How can I do that ?
    Please give me some ideas how to do that .
    Thanks in advance
    Edited by: m.parthiban on Mar 5, 2008 1:20 PM

    ejp, thanks for your reply . can you please explain me bit more by providing code snippet ?
    This is what I have done till now :
    MyServer:
    package connection;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class MyServer {
          * @param args
         public static void main(String[] args) {
              String ss ="",temp ="";
              Socket clientLink=null;
              try {
                        ServerSocket sockServer = new ServerSocket(6000);
                        while(true) {
                             clientLink = sockServer.accept();
                             System.out.println("Connection Established");
                             InputStreamReader isr = new InputStreamReader(clientLink.getInputStream());
                             BufferedReader bufReader = new BufferedReader(isr);
    //                         System.out.println("buf "+bufReader.readLine());
                             try {
                                  while ((temp=bufReader.readLine())!=null) {
                                       ss+=temp;
                                       System.out.println("ss   "+ss+"Temp "+temp );
                                  System.out.println("Client > "+ss);
                             } catch (IOException e) {
                                  System.out.println("while reading");
                                  e.printStackTrace();
                             OutputStreamWriter osw = new OutputStreamWriter(clientLink.getOutputStream());
                             PrintWriter pw = new PrintWriter(osw,true);
                             pw.write("Welcome -by Server !!!");
                             pw.flush();
                             clientLink.shutdownOutput();
                             clientLink.close();
              } catch (IOException e) {
                   System.out.println("Can't able to connect");
                   e.printStackTrace();
    }MyClient:
    package connection;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.Socket;
    import javax.swing.JOptionPane;
    public class MyClient {
          * @param args
         public static void main(String[] args) {
              try {
                   String serverMsg="",temp="";
                   Socket client = new Socket("127.0.0.1",6000);
                   PrintWriter pw = new PrintWriter(client.getOutputStream(),true);
                   pw.write("Hi ,Accecpt me");
                   pw.flush();
    //               pw.close();
                   client.shutdownOutput();
                   InputStreamReader isr  = new InputStreamReader(client.getInputStream());
                   BufferedReader bufRead = new BufferedReader(isr);
                   while ((temp=bufRead.readLine())!=null) {
                        serverMsg +=temp;
                   System.out.println("Server > "+serverMsg);
                   JOptionPane.showMessageDialog(null, serverMsg);
                   client.shutdownInput();
                   client.close();
              } catch (IOException e) {
                   System.out.println("Failed to connect");
                   e.printStackTrace();
    }Once again thanks for the time you spend to reply me.

  • Thread problem in JavaNIO client server application

    **Dear experts,**
    I have problem with server which is nonblocking nio server, after registering one client the server is not registering other clients can some body told me, what is going on why sever is not showing any activity*
    this is Tour proxy class which is at client site and dealing with server and updating GUI on client site:*
    public void run() {
              connect(host);
              running = true;
              while (running) {
                   readIncomingMessages();
                   // nap for a bit
                   try {
                        Thread.sleep(50);
                   catch (InterruptedException ie) {
         } this is GUI which is dealing with Tourproxy
    class WrapNetTour3D
    void createSceneGraph(String userName, String tourFnm,
                                                 double xPosn, double zPosn)
      // initialize the scene
        sceneBG = new BranchGroup();
        bounds = new BoundingSphere(new Point3d(0,0,0), BOUNDSIZE);
        // to allow clients to be added/removed from the world at run time
        sceneBG.setCapability(Group.ALLOW_CHILDREN_READ);
        sceneBG.setCapability(Group.ALLOW_CHILDREN_WRITE);
        sceneBG.setCapability(Group.ALLOW_CHILDREN_EXTEND);
        lightScene();         // add the lights
        addBackground();      // add the sky
        sceneBG.addChild( new CheckerFloor().getBG() );  // add the floor
        makeScenery(tourFnm);      // add scenery and obstacles
        TP = new TourProxy("localhost",this,obs);
        makeContact();     // contact server (after Obstacles object created)
        addTourist(userName, xPosn, zPosn);     
                                // add the user-controlled 3D sprite
        sceneBG.compile();   // fix the scene
      } // end of createSceneGraph()
    private void makeContact()
      /* Contact the server, and set up a TourProxy to monitor the
         server. */
        try {
               TP.start();
        catch(Exception e)
        { System.out.println("No contact with server");
          System.exit(0);
      }  // end of makeContact()
    ....} this is class which is initializing the above class WrapNetTour3D:
      public NetTour3D(String args[])
        super("3D NetTour");
        processArgs(args);
        setTitle( getTitle() + " for " + userName);
        Container c = getContentPane();
        c.setLayout( new BorderLayout() );
        w3d = new WrapNetTour3D(userName, tourFnm, xPosn, zPosn);
        c.add(w3d, BorderLayout.CENTER);
         addWindowListener( new WindowAdapter() {
           public void windowClosing(WindowEvent e)
           { w3d.closeLink(); }
        pack();
        setResizable(false);    // fixed size display
        setVisible(true);
      } // end of NetTour3D() and this is server:
    public NIOTourServer( String string, int port) throws IOException {
              this.addr = string;
              this.port = port;
              writeBuffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
              dataMap = new HashMap<SocketChannel, List<byte[]>>();
              clients = new LinkedList();
              userName = "?";
              startServer();
         private void startServer() throws IOException {
              // create selector and channel
              this.selector = Selector.open();
              ServerSocketChannel serverChannel = ServerSocketChannel.open();
              serverChannel.configureBlocking(false);
              // bind to port
              InetSocketAddress listenAddr = new InetSocketAddress(this.addr,
                        this.port);
              serverChannel.socket().bind(listenAddr);
              serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);
              log("Echo server ready. Ctrl-C to stop.");
              // processing
              while (true) {
                   // wait for events
                   this.selector.select();
                   // wakeup to work on selected keys
                   Iterator keys = this.selector.selectedKeys().iterator();
                   while (keys.hasNext()) {
                        SelectionKey key = (SelectionKey) keys.next();
                        // this is necessary to prevent the same key from coming up
                        // again the next time around.
                        keys.remove();
                        if (!key.isValid()) {
                             continue;
                        if (key.isAcceptable()) {
                             this.accept(key);
                        } else if (key.isReadable()) {
                             this.read(key);
                        } else if (key.isWritable()) {
                             //this.write(key);
         private void accept(SelectionKey key) throws IOException {
              ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
              SocketChannel channel = serverChannel.accept();
              clients.add(channel);
              log.info("got connection from: " + channel.socket().getInetAddress());
              channel.configureBlocking(false);
              // write welcome message
              channel.write(ByteBuffer.wrap("Welcome, this is the Tour server\r\n"
                        .getBytes("US-ASCII")));
              Socket socket = channel.socket();
              SocketAddress remoteAddr = socket.getRemoteSocketAddress();
              log.info("Connected to: " + remoteAddr);
              // register channel with selector for further IO
              dataMap.put(channel, new ArrayList<byte[]>());
              channel.register(this.selector, SelectionKey.OP_READ);
         private void sendMessage(SocketChannel channel, String mesg) {
              prepWriteBuffer(mesg);
              channelWrite(channel, writeBuffer);
         private void read(SelectionKey key) throws IOException {
              try {
                   SocketChannel channel = (SocketChannel) key.channel();
                   ByteBuffer buffer = ByteBuffer.allocate(4192);
                   int numRead = -1;
                   // read from the channel into our buffer
                   numRead = channel.read(buffer);
                   // check for end-of-stream
                   if (numRead == -1) {
                        log.info("disconnect: " + channel.socket().getInetAddress()
                                  + ", end-of-stream");
                        channel.close();
                        clients.remove(channel);
                        sendBroadcastMessage("logout: "
                                  + channel.socket().getInetAddress(), channel);
                   } else {
                        byte[] data = new byte[numRead];
                        System.arraycopy(buffer.array(), 0, data, 0, numRead);
                        String dataReturn = new String(data, "US-ASCII");
                        log("Got: " + dataReturn);
                        processClient(dataReturn,channel);
              } catch (IOException ioe) {
                   log.warn("error during select(): ", ioe);
              } catch (Exception e) {
                   log.error("exception in run()", e);
         private void processClient(String line,SocketChannel from)
         /* Stop when the input stream closes (is null) or "bye" is sent
               Otherwise pass the input to doRequest(). */
              //String line;
              boolean done = false;
              while (!done) {
                   // if((line = in.readLine()) == null)
                   if(line == null)
                        done = true;
                   else {
                        // System.out.println(userName + " received msg: " + line);
                        if (line.trim().equals("bye"))
                             done = true;
                        else
                             doRequest(line.trim(), from);
         }  // end of processClient()
    ...} i thought there is some problem with threads
    can somebody tell me how can i deal with it, as i m new newbie and how could i avoid problems in such design and complex application so that i am able to complete this application
    please help,
    thanks a lot
    jibbylala
    Edited by: 805185 on Nov 23, 2010 10:43 AM
    Edited by: 805185 on Nov 23, 2010 11:36 AM

    ejp:Here you are assuming that the socket is readable. Check it. You also need to check for isConnectable(), and if true, try finishConnect(), and if that succeeds deregister OP_CONNECT and register OP_READ.
    where i do this or it should be  done in connect method() or in readIncomingMessages() .
    the current problem is connecting 2nd client.
    i thought the other steps came later
    i changed the connect method like this :
    private void connect(String hostname) {
              try {
                   InetAddress addr = InetAddress.getByName(hostname);
                   int mnInterestOps = 0;
                   try
                        channel = SocketChannel.open();
                        channel.configureBlocking(false);
                        InetSocketAddress mxRemoteAddress = new InetSocketAddress(addr, PORT);
                        boolean t_connect = channel.connect(mxRemoteAddress);
                        if (t_connect)
                             System.out.println("connected");
                             mnInterestOps = SelectionKey.OP_WRITE | SelectionKey.OP_READ ;
                        else
                             mnInterestOps = SelectionKey.OP_CONNECT;
                        //create the selector
                        readSelector= SelectorProviderImpl.provider().openSelector();
                        //register the channel with the selector indicating an interest
                        SelectionKey x_key = channel.register(readSelector, mnInterestOps);
                        //select loop
                        while(true)
                             //block until connect response is received
                             int selectReturn = readSelector.select(0);
                             if (selectReturn == 0)
                                  System.out.println("select returned 0");
                             Set myKeys = readSelector.selectedKeys();
                             if (!myKeys.isEmpty())
                                  Iterator x_readyKeysIterator = myKeys.iterator();
                                  // Iterate over the set of keys for which events are available
                                  while (x_readyKeysIterator.hasNext())
                                       SelectionKey x_selectionKey = (SelectionKey) x_readyKeysIterator.next();
                                       // Remove selected key
                                       x_readyKeysIterator.remove();
                                       if (x_selectionKey.isValid())
                                            if (x_selectionKey.isConnectable()) {
                                                 channel.finishConnect();
                                                 System.out.println("connection 2 accepted");
                                            else if (x_selectionKey.isWritable()) {
                                                 System.out.println("writable channel, select return =" + selectReturn);
                                                 x_selectionKey.cancel();
                                            else if (x_selectionKey.isReadable()) {
                                                 System.out.println("readable channel" + selectReturn);
                                       else
                                            //cancel the channel registration with this selector
                                            x_selectionKey.cancel();
                                            System.out.println("key not valid");
                        } //end while(true)
                   } //end try block
                   catch (Exception ex)
                        System.out.println("exception " + ex);
              catch (UnknownHostException uhe) {
                   uhe.printStackTrace();
              catch (Exception e) {e.printStackTrace();
         } but now i m getting NPE HERE in tourproxy class.
    this is method which is calling channelWrite() and this method sendMessage()  i m calling from different other gui classes and i don't think so that i need  to pass the channel from there:
    void sendMessage(String mesg) {
              prepWriteBuffer(mesg);
              channelWrite(channel, writeBuffer);
    private void channelWrite(SocketChannel channel, ByteBuffer writeBuffer) {
    nbytes += channel.write(writeBuffer); *//channel is null here*
    } *can you just  tell me why it is null as i m populating it in connect method or what should i do?
    PS: i already created chat application with javaNIO....
    The output of this application  is nothing but a sprite which has to move simultaneously on two clients but it is not because server can't register more than one client.

  • Need combobox with a Jtable to view client & server files

    Hellow Everybody,
    I am quite new to Java, although I have experience with other
    programming languages.
    I have searched for tutorials, code, examples etc. but have not found
    much that can help me so far. I am a BCA student & I am appearing for my last year exams. I studied about various Java programs in my course and I decided to make a Swing based FTP Server. Although I not expert in Java , but I have learnt the network programming very much clearly, and that�s why by the help these I wrote a program but it not complete. I have given the program below.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Cursor;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.StringTokenizer;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.JProgressBar;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.border.BevelBorder;
    import javax.swing.border.EmptyBorder;
    import sun.net.TelnetInputStream;
    import sun.net.ftp.FtpClient;
    public class Client extends JFrame {
    public static int BUFFER_SIZE = 10240;
    protected JTextField userNameTextField = new JTextField("anonymous");
    protected JPasswordField passwordTextField = new JPasswordField(10);
    protected JTextField urlTextField = new JTextField(20);
    protected JTextField fileTextField = new JTextField(10);
    protected JTextArea monitorTextArea = new JTextArea(5, 20);
    protected JProgressBar m_progress = new JProgressBar();
    protected JButton putButton = new JButton("Upload <<");
    protected JButton getButton;
    protected JButton fileButton = new JButton("File");
    protected JButton closeButton = new JButton("Close");
    protected JFileChooser fileChooser = new JFileChooser();
    protected FtpClient ftpClient;
    protected String localFileName;
    protected String remoteFileName;
    public Client() {
    super("FTP Client");
    JPanel p = new JPanel();
    p.setBorder(new EmptyBorder(5, 5, 5, 5));
    p.add(new JLabel("User name:"));
    p.add(userNameTextField);
    p.add(new JLabel("Password:"));
    p.add(passwordTextField);
    p.add(new JLabel("URL:"));
    p.add(urlTextField);
    p.add(new JLabel("File:"));
    p.add(fileTextField);
    monitorTextArea.setEditable(false);
    JScrollPane ps = new JScrollPane(monitorTextArea);
    p.add(ps);
    m_progress.setStringPainted(true);
    m_progress.setBorder(new BevelBorder(BevelBorder.LOWERED, Color.white,
    Color.gray));
    m_progress.setMinimum(0);
    JPanel p1 = new JPanel(new BorderLayout());
    p1.add(m_progress, BorderLayout.CENTER);
    p.add(p1);
    ActionListener lst = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if (connect()) {
    Thread uploader = new Thread() {
    public void run() {
    putFile();
    disconnect();
    uploader.start();
    putButton.addActionListener(lst);
    putButton.setMnemonic('U');
    p.add(putButton);
    getButton = new JButton("Download >>");
    lst = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if (connect()) {
    Thread downloader = new Thread() {
    public void run() {
    getFile();
    disconnect();
    downloader.start();
    getButton.addActionListener(lst);
    getButton.setMnemonic('D');
    p.add(getButton);
    lst = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if (fileChooser.showSaveDialog(Client.this) != JFileChooser.APPROVE_OPTION)
    return;
    File f = fileChooser.getSelectedFile();
    fileTextField.setText(f.getPath());
    fileButton.addActionListener(lst);
    fileButton.setMnemonic('f');
    p.add(fileButton);
    lst = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if (ftpClient != null)
    disconnect();
    else
    System.exit(0);
    closeButton.addActionListener(lst);
    closeButton.setDefaultCapable(true);
    closeButton.setMnemonic('g');
    p.add(closeButton);
    getContentPane().add(p, BorderLayout.CENTER);
    fileChooser.setCurrentDirectory(new File("."));
    fileChooser
    .setApproveButtonToolTipText("Select file for upload/download");
    WindowListener wndCloser = new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    disconnect();
    System.exit(0);
    addWindowListener(wndCloser);
    setSize(720, 240);
    setVisible(true);
    public void setButtonStates(boolean state) {
    putButton.setEnabled(state);
    getButton.setEnabled(state);
    fileButton.setEnabled(state);
    protected boolean connect() {
    monitorTextArea.setText("");
    setButtonStates(false);
    closeButton.setText("Cancel");
    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    String user = userNameTextField.getText();
    if (user.length() == 0) {
    setMessage("Please enter user name");
    setButtonStates(true);
    return false;
    String password = new String(passwordTextField.getPassword());
    String sUrl = urlTextField.getText();
    if (sUrl.length() == 0) {
    setMessage("Please enter URL");
    setButtonStates(true);
    return false;
    localFileName = fileTextField.getText();
    // Parse URL
    int index = sUrl.indexOf("//");
    if (index >= 0)
    sUrl = sUrl.substring(index + 2);
    index = sUrl.indexOf("/");
    String host = sUrl.substring(0, index);
    sUrl = sUrl.substring(index + 1);
    String sDir = "";
    index = sUrl.lastIndexOf("/");
    if (index >= 0) {
    sDir = sUrl.substring(0, index);
    sUrl = sUrl.substring(index + 1);
    remoteFileName = sUrl;
    try {
    setMessage("Connecting to host " + host);
    ftpClient = new FtpClient(host);
    ftpClient.login(user, password);
    setMessage("User " + user + " login OK");
    setMessage(ftpClient.welcomeMsg);
    ftpClient.cd(sDir);
    setMessage("Directory: " + sDir);
    ftpClient.binary();
    return true;
    } catch (Exception ex) {
    setMessage("Error: " + ex.toString());
    setButtonStates(true);
    return false;
    protected void disconnect() {
    if (ftpClient != null) {
    try {
    ftpClient.closeServer();
    } catch (IOException ex) {
    ftpClient = null;
    Runnable runner = new Runnable() {
    public void run() {
    m_progress.setValue(0);
    putButton.setEnabled(true);
    getButton.setEnabled(true);
    fileButton.setEnabled(true);
    closeButton.setText("Close");
    Client.this.setCursor(Cursor
    .getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    SwingUtilities.invokeLater(runner);
    protected void getFile() {
    if (localFileName.length() == 0) {
    localFileName = remoteFileName;
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    fileTextField.setText(localFileName);
    byte[] buffer = new byte[BUFFER_SIZE];
    try {
    int size = getFileSize(ftpClient, remoteFileName);
    if (size > 0) {
    setMessage("File " + remoteFileName + ": " + size + " bytes");
    setProgressMaximum(size);
    } else
    setMessage("File " + remoteFileName + ": size unknown");
    FileOutputStream out = new FileOutputStream(localFileName);
    InputStream in = ftpClient.get(remoteFileName);
    int counter = 0;
    while (true) {
    int bytes = in.read(buffer);
    if (bytes < 0)
    break;
    out.write(buffer, 0, bytes);
    counter += bytes;
    if (size > 0) {
    setProgressValue(counter);
    int proc = (int) Math
    .round(m_progress.getPercentComplete() * 100);
    setProgressString(proc + " %");
    } else {
    int kb = counter / 1024;
    setProgressString(kb + " KB");
    out.close();
    in.close();
    } catch (Exception ex) {
    setMessage("Error: " + ex.toString());
    protected void putFile() {
    if (localFileName.length() == 0) {
    setMessage("Please enter file name");
    byte[] buffer = new byte[BUFFER_SIZE];
    try {
    File f = new File(localFileName);
    int size = (int) f.length();
    setMessage("File " + localFileName + ": " + size + " bytes");
    setProgressMaximum(size);
    FileInputStream in = new FileInputStream(localFileName);
    OutputStream out = ftpClient.put(remoteFileName);
    int counter = 0;
    while (true) {
    int bytes = in.read(buffer);
    if (bytes < 0)
    break;
    out.write(buffer, 0, bytes);
    counter += bytes;
    setProgressValue(counter);
    int proc = (int) Math
    .round(m_progress.getPercentComplete() * 100);
    setProgressString(proc + " %");
    out.close();
    in.close();
    } catch (Exception ex) {
    setMessage("Error: " + ex.toString());
    protected void setMessage(final String str) {
    if (str != null) {
    Runnable runner = new Runnable() {
    public void run() {
    monitorTextArea.append(str + '\n');
    monitorTextArea.repaint();
    SwingUtilities.invokeLater(runner);
    protected void setProgressValue(final int value) {
    Runnable runner = new Runnable() {
    public void run() {
    m_progress.setValue(value);
    SwingUtilities.invokeLater(runner);
    protected void setProgressMaximum(final int value) {
    Runnable runner = new Runnable() {
    public void run() {
    m_progress.setMaximum(value);
    SwingUtilities.invokeLater(runner);
    protected void setProgressString(final String string) {
    Runnable runner = new Runnable() {
    public void run() {
    m_progress.setString(string);
    SwingUtilities.invokeLater(runner);
    public static int getFileSize(FtpClient client, String fileName)
    throws IOException {
    TelnetInputStream lst = client.list();
    String str = "";
    fileName = fileName.toLowerCase();
    while (true) {
    int c = lst.read();
    char ch = (char) c;
    if (c < 0 || ch == '\n') {
    str = str.toLowerCase();
    if (str.indexOf(fileName) >= 0) {
    StringTokenizer tk = new StringTokenizer(str);
    int index = 0;
    while (tk.hasMoreTokens()) {
    String token = tk.nextToken();
    if (index == 4)
    try {
    return Integer.parseInt(token);
    } catch (NumberFormatException ex) {
    return -1;
    index++;
    str = "";
    if (c <= 0)
    break;
    str += ch;
    return -1;
    public static void main(String argv[]) {
    new Client();
    The above given code is not yet complete. I want some specific features to be implemented in this code that is given below.
    1.     A login Gridlayout or Borderlayout & within it the username & password textfield.
    2.     When the username and password will request to server and if it will success then the textfields of the username & password have to be disable.
    3 . Two Combobox. One will give client directories and files and another
    will give the server directories and files.
    4 . Below the Combobox two JTable will be given & the tables wll show the
    client and server directories and files.
    Could anybody give me the codes that I want. If anybody check this code please help me????
    With Regards,
    DILLU

    Well Mr Michael_Dunn,
    Thanks for responding my query. First of all I would like to tell that
    this FTP server is going to be my project and that's why I am submmiting my question. I told in my points that I want a Jcombobox & a JTable for displaying that files & directories. whenever I set the directories in the combobox the files will be displayed in the JTable
    I hope you understand my point

  • Multicast server/client over wan

    Ok, first of I am kinda new in programming network stuff.
    Then I am gonna try to be clear in the things that I am trying to accomplish.
    The environement.
    I have a machine A that has 2 interfaces :
    eth0 Link encap:Ethernet HWaddr 00:0F:20:96:CE:96
    inet addr:192.168.1.49 Bcast:192.168.1.255 Mask:255.255.255.0
    UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
    RX packets:2328871 errors:0 dropped:0 overruns:0 frame:0
    TX packets:355492 errors:0 dropped:0 overruns:0 carrier:0
    collisions:0 txqueuelen:1000
    RX bytes:178361234 (170.0 Mb) TX bytes:34186479 (32.6 Mb)
    Interrupt:11
    eth2 Link encap:Ethernet HWaddr 00:04:23:45:74:EC
    inet addr:192.168.2.2 Bcast:192.168.2.255 Mask:255.255.255.0
    UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
    RX packets:813915 errors:0 dropped:0 overruns:0 frame:0
    TX packets:7538202 errors:0 dropped:0 overruns:0 carrier:0
    collisions:0 txqueuelen:1000
    RX bytes:53318289 (50.8 Mb) TX bytes:1092719670 (1042.0 Mb)
    Interrupt:15 Base address:0x3000 Memory:f7ee0000-f7f00000
    lo Link encap:Local Loopback
    inet addr:127.0.0.1 Mask:255.0.0.0
    UP LOOPBACK RUNNING MTU:16436 Metric:1
    RX packets:56496 errors:0 dropped:0 overruns:0 frame:0
    TX packets:56496 errors:0 dropped:0 overruns:0 carrier:0
    collisions:0 txqueuelen:0
    RX bytes:7952617 (7.5 Mb) TX bytes:7952617 (7.5 Mb)
    This machine is connected thru a router
    The routers connects to a WAN with MULTICAST enabled
    then another router to which the second machine is connected
    MACHINE B
    eth0 Link encap:Ethernet HWaddr 00:0F:20:96:0F:94
    inet addr:192.168.1.58 Bcast:192.168.1.255 Mask:255.255.255.0
    UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
    RX packets:2322957 errors:0 dropped:0 overruns:0 frame:0
    TX packets:363116 errors:0 dropped:0 overruns:0 carrier:0
    collisions:0 txqueuelen:1000
    RX bytes:177550404 (169.3 Mb) TX bytes:33507499 (31.9 Mb)
    Interrupt:30
    eth2 Link encap:Ethernet HWaddr 00:04:23:45:78:90
    inet addr:192.168.3.2 Bcast:192.168.3.255 Mask:255.255.255.0
    UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
    RX packets:160838 errors:0 dropped:0 overruns:0 frame:0
    TX packets:6781 errors:0 dropped:0 overruns:0 carrier:0
    collisions:0 txqueuelen:1000
    RX bytes:11450177 (10.9 Mb) TX bytes:746369 (728.8 Kb)
    Interrupt:28 Base address:0x3000 Memory:f7ee0000-f7f00000
    lo Link encap:Local Loopback
    inet addr:127.0.0.1 Mask:255.0.0.0
    UP LOOPBACK RUNNING MTU:16436 Metric:1
    RX packets:158 errors:0 dropped:0 overruns:0 frame:0
    TX packets:158 errors:0 dropped:0 overruns:0 carrier:0
    collisions:0 txqueuelen:0
    RX bytes:23916 (23.3 Kb) TX bytes:23916 (23.3 Kb)
    The two machine are on different networks.
    My goal is to have Machine A send multicast data thru eth2 to be sent in the wan and to be received by Machine B on eth2 too.
    Obviously the two machine are on separated networks.
    I have tried everything I could but I cannot get machine B to pickup the messages sent by A. It worked fine when on the same LAN but not over WAN.
    The multicast address that I use it 239.55.55.80 and the port 4445.
    I think I have a problem to link the interface to my app ( I used setInterface and setNetworkinterface but nithing.) Also I cannot firgure out if the things that I am doing wrong are on the server or the client.
    Here is the code for the sever and client.
    SERVER
    package com.cme.multicastijector.server;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2004</p>
    * <p>Company: </p>
    * @author not attributable
    * @version 1.0
    import java.net.*;
    import java.util.*;
    public class MulticastOutputSocket {
    private int m_multicastPort = 0;
    private MulticastSocket m_multicastSocket = null;
    private InetAddress m_interfaceAddress = null;
    private InetAddress m_multicastAddress = null;
    private InetSocketAddress m_inetSocketAddress = null;
    private int m_bufferSize = 0;
    private byte[] m_outputBuffer = null;
    private DatagramPacket m_packet = null;
    public MulticastOutputSocket(int portNumber,String interfaceAddress,String multicastAddress,int bufferSize) throws Exception{
    System.out.println("\nStarting multicast output socket");
    m_multicastPort = portNumber;
    m_interfaceAddress = InetAddress.getByName(interfaceAddress);
    m_multicastAddress = InetAddress.getByName(multicastAddress);
    m_bufferSize = bufferSize;
    m_inetSocketAddress = new InetSocketAddress(m_multicastAddress,m_multicastPort);
    m_multicastSocket = new MulticastSocket (m_multicastPort);
    // m_multicastSocket.joinGroup(m_inetSocketAddress,NetworkInterface.getByInetAddress(m_interfaceAddress));
    m_multicastSocket.setNetworkInterface(NetworkInterface.getByInetAddress(m_interfaceAddress));
    // m_multicastSocket.setLoopbackMode(false);
    // m_multicastSocket.setTimeToLive(32);
    Enumeration e = NetworkInterface.getNetworkInterfaces();
    while (e.hasMoreElements()){
    System.out.println(e.nextElement().toString());
    System.out.println("Interface Address = " + m_interfaceAddress);
    System.out.println("Multicast Address = " + m_multicastAddress);
    System.out.println("Port = " + m_multicastPort);
    System.out.println("BufferSize = " + m_bufferSize);
    System.out.println("MulticastSockect initialized.\n");
    public void sendData(String data) throws Exception{
    m_outputBuffer = new byte[m_bufferSize];
    m_outputBuffer = data.getBytes();
    //m_packet = new DatagramPacket(m_outputBuffer, m_outputBuffer.length);
    m_packet = new DatagramPacket(m_outputBuffer, m_outputBuffer.length, m_inetSocketAddress);
    m_multicastSocket.send(m_packet);
    public void closeSocket() throws Exception {
    //m_multicastSocket.leaveGroup(m_multicastAddress);
    //m_multicastSocket.leaveGroup(m_inetSocketAddress,NetworkInterface.getByInetAddress(m_interfaceAddress));
    m_multicastSocket.close();
    CLIENT
    package com.cme.multicastijector.client;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2004</p>
    * <p>Company: </p>
    * @author not attributable
    * @version 1.0
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class MulticastClient {
    private Properties m_prop = null;
    private MulticastSocket m_multicastSocket = null;
    private InetAddress m_interfaceAddress = null;
    private InetAddress m_multicastAddress = null;
    private InetSocketAddress m_inetSocketAddress = null;
    private int m_multicastPort = 0;
    private int m_bufferSize = 0;
    private int m_previousSeq = 0;
    private boolean m_isFirst = true;
    private int m_actualseq = 0;
    private int m_msgLost = 0;
    private int m_messagesReceived = 0;
    private Object m_seqLock = new Object();
    private Object m_msgLock = new Object();
    public MulticastClient(Properties properties) throws Exception{
    m_prop = properties;
    init();
    new TpsCalculator();
    receiveData();
    private void init() throws Exception{
    m_multicastPort = Integer.parseInt(m_prop.getProperty("MULTICAST_PORT"));
    m_multicastAddress = InetAddress.getByName(m_prop.getProperty("MULTICAST_ADDRESS"));
    m_interfaceAddress = InetAddress.getByName(m_prop.getProperty("INTERFACE_ADDRESS"));
    m_bufferSize = Integer.parseInt(m_prop.getProperty("BUFFER_SIZE"));
    m_inetSocketAddress = new InetSocketAddress(m_multicastAddress,m_multicastPort);
    m_multicastSocket = new MulticastSocket (m_multicastPort);
    // System.out.println("DEFAULT INTERFACE : " + m_multicastSocket.getInterface() );
    // System.out.println("DEFAULT INTERFACE : " + m_multicastSocket.getNetworkInterface() );
    // m_multicastSocket.setInterface(m_interfaceAddress);
    // m_multicastSocket.setNetworkInterface(NetworkInterface.getByInetAddress(m_interfaceAddress));
    // System.out.println("DEFAULT INTERFACE : " + m_multicastSocket.getInterface() );
    // System.out.println("DEFAULT INTERFACE : " + m_multicastSocket.getNetworkInterface() );
    m_multicastSocket.joinGroup(m_inetSocketAddress,NetworkInterface.getByInetAddress(m_interfaceAddress));
    // m_multicastSocket.joinGroup(m_multicastAddress);
    System.out.println("Interface Address = " + m_interfaceAddress);
    System.out.println("Multicast Address = " + m_multicastAddress);
    System.out.println("Port = " + m_multicastPort);
    System.out.println("BufferSize = " + m_bufferSize);
    private void receiveData() throws Exception{
    try {
    String received = null;
    byte[] inputBuffer = null;
    DatagramPacket packet = null;
    while(true){
    inputBuffer = new byte[m_bufferSize];
    packet = new DatagramPacket(inputBuffer, inputBuffer.length, m_inetSocketAddress);
    m_multicastSocket.receive(packet);
    received = new String(packet.getData());
    m_messagesReceived++;
    synchronized(m_seqLock){
    m_actualseq = getSequence(received);
    checkSequence(m_actualseq);
    catch (Exception ex) {
    ex.printStackTrace();
    m_multicastSocket.close();
    private int getSequence(String data){
    return Integer.parseInt(data.substring(0,15));
    private void checkSequence(int actual){
    if(m_isFirst){
    m_isFirst = false;
    m_previousSeq = actual;
    else{
    if ( (m_previousSeq + 1) != actual) {
    synchronized(m_msgLock){
    m_msgLost += (actual - m_previousSeq)-1;
    m_previousSeq = actual;
    private class TpsCalculator extends TimerTask{
    private Timer aTimer;
    private int previousSeq = 0;
    private int tpsSeq = 0;
    private int tpsRec = 0;
    private boolean first = true;
    private int msglost = 0;
    private int previousMsgRec = 0;
    private int actualMsgRec = 0;
    public TpsCalculator(){
    aTimer = new Timer();
    aTimer.scheduleAtFixedRate(this,new Date(),1000);
    System.out.println("#####################################################");
    System.out.println("time,tps from sequences, actual tps,total msg received,msglost");
    public void run(){
    actualMsgRec = m_messagesReceived;
    tpsRec = actualMsgRec - previousMsgRec;
    previousMsgRec = actualMsgRec;
    if(first){
    synchronized(m_seqLock){
    previousSeq = m_actualseq;
    first = false;
    else{
    synchronized(m_msgLock){
    msglost = m_msgLost;
    m_msgLost = 0;
    synchronized(m_seqLock){
    tpsSeq = m_actualseq - previousSeq;
    previousSeq = m_actualseq;
    System.out.println(new Date()+","+tpsSeq + "," + tpsRec + "," + m_messagesReceived + "," + msglost);
    Thanks for your help.
    This is really important for the project I am working on.
    Thanks again

    never Mind I found the issue
    The default value for TTL is 1.
    I was going thru multiple routers so I incremented the value and it worked
    thanks

  • File transfer, read write through sockets in client server programming java

    Hello All, need help again.
    I am trying to create a Client server program, where, the Client first sends a file to Server, on accepting the file, the server generates another file(probably xml), send it to the client as a response, the client read the response xml, parse it and display some data. now I am successful sending the file to the server, but could not figure out how the server can create and send a xml file and send it to the client as response, please help. below are my codes for client and server
    Client side
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.BufferedReader;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    public class XMLSocketC
         public static void main(String[] args) throws IOException
              //Establish a connection to socket
              Socket toServer = null;
              String host = "127.0.0.1";     
              int port = 4444;
              try
                   toServer = new Socket(host, port);
                   } catch (UnknownHostException e) {
                System.err.println("Don't know about host: localhost.");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to host.");
                System.exit(1);
              //Send file over Socket
            //===========================================================
            BufferedInputStream fileIn = null;
              BufferedOutputStream out = null;
              // File to be send over the socket.
              File file = new File("c:/xampp/htdocs/thesis/sensorList.php");
              // Checking for the file to be sent.
              if (!file.exists())
                   System.out.println("File doesn't exist");
                   System.exit(0);
              try
                   // InputStream to read the file
                   fileIn = new BufferedInputStream(new FileInputStream(file));
              }catch(IOException eee)
                   System.out.println("Problem, kunne ikke lage fil");
              try
                   InetAddress adressen = InetAddress.getByName(host);
                   try
                        System.out.println("Establishing Socket Connection");
                        // Opening Socket
                        Socket s = new Socket(adressen, port);
                        System.out.println("Socket is clear and available.....");
                        // OutputStream to socket
                        out = new BufferedOutputStream(s.getOutputStream());
                        byte[] buffer = new byte[1024];
                        int numRead;
                        //Checking if bytes available to read to the buffer.
                        while( (numRead = fileIn.read(buffer)) >= 0)
                             // Writes bytes to Output Stream from 0 to total number of bytes
                             out.write(buffer, 0, numRead);
                        // Flush - send file
                        out.flush();
                        // close OutputStream
                        out.close();
                        // close InputStrean
                        fileIn.close();
                   }catch (IOException e)
              }catch(UnknownHostException e)
                   System.err.println(e);
            //===========================================================
            //Retrieve data from Socket.
              //BufferedReader in = new BufferedReader(new InputStreamReader(toServer.getInputStream()));
              DataInputStream in = new DataInputStream(new BufferedInputStream(toServer.getInputStream()));
              //String fromServer;
            //Read from the server and prints.
              //Receive text from server
              FileWriter fr = null;
              String frn = "xxx_response.xml";
              try {
                   fr = new FileWriter(frn);
              } catch (IOException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
              try{
                   String line = in.readUTF();                    //.readLine();
                   System.out.println("Text received :" + line);
                   fr.write(line);
              } catch (IOException e){
                   System.out.println("Read failed");
                   System.exit(1);
            in.close();
            toServer.close();
    public class XMLSocketS
          public static void main(String[] args) throws IOException
              //Establish a connection to socket
               ServerSocket serverSocket = null;
                 try {
                     serverSocket = new ServerSocket(4444);
                 } catch (IOException e) {
                     System.err.println("Could not listen on port: 4444.");
                     System.exit(1);
              Socket clientLink = null;
              while (true)
                        try
                             clientLink = serverSocket.accept();
                           System.out.println("Server accepts");
                             BufferedInputStream inn = new BufferedInputStream(clientLink.getInputStream());
                             BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:/xampp/htdocs/received_from_client.txt")));
                             byte[] buff = new byte[1024];
                             int readMe;
                             while( (readMe = inn.read(buff)) >= 0)
                             {     //reads from input stream, writes the file to disk
                                  ut.write(buff, 0, readMe);
                             // close the link to client
                             clientLink.close();                         
                             // close InputStream
                             inn.close();                         
                             // flush
                             ut.flush();                         
                             // close OutputStream
                             ut.close();     
                             //Sending response to client     
                             //============================================================
                             //============================================================
                             System.out.println("File received");
              }catch(IOException ex)
              {System.out.println("Exception.");}
                        finally
                             try
                                  if (clientLink != null) clientLink.close();
                             }catch(IOException e) {}
                 clientLink.close();
                 //serverSocket.close();
    }

    SERVER
    import java.net.*;
    import java.io.*;
    public class XMLSocketS
          public static void main(String[] args) throws IOException
                   //Establish a connection to socket
               ServerSocket serverSocket = null;
                 try {
                     serverSocket = new ServerSocket(4545);
                 } catch (IOException e) {
                     System.err.println("Could not listen on port: 4444.");
                     System.exit(1);
              Socket clientLink = null;
                  try
                             clientLink = serverSocket.accept();
                         System.out.println("Server accepts the client request.....");
                         BufferedInputStream inn = new BufferedInputStream(clientLink.getInputStream());
                             BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:/xampp/htdocs/received_from_client.txt")));
                             byte[] buff = new byte[1024];
                             int readMe;
                             while( (readMe = inn.read(buff)) >= 0)
                             {     //reads from input stream, writes the file to disk
                                  ut.write(buff, 0, readMe);
                             ut.flush();                         
                             //Sending response to client     
                             //============================================================
                             BufferedInputStream ftoC = null;
                             BufferedOutputStream outtoC = null;
                             // File to be send over the socket.
                             File file = new File("c:/xampp/htdocs/thesis/user_registration_response.xml");
                             try
                                  // InputStream to read the file
                                   ftoC = new BufferedInputStream(new FileInputStream(file));
                             }catch(IOException eee)
                             {System.out.println("Problem reading file");}
                             // OutputStream to socket
                             outtoC = new BufferedOutputStream(clientLink.getOutputStream());
                             byte[] buffer = new byte[1024];
                             int noRead;
                             //Checking if bytes available to read to the buffer.
                             while( (noRead = ftoC.read(buffer)) >= 0)
                                  // Writes bytes to Output Stream from 0 to total number of bytes
                                  outtoC.write(buffer, 0, noRead);
                             outtoC.flush();
                             //============================================================
                             System.out.println("File received");
              }catch(IOException ex)
              {System.out.println("Exception.");}
                        finally
                             try
                                  if (clientLink != null) clientLink.close();
                             }catch(IOException e) {}
                 clientLink.close();
                 //serverSocket.close();
          }CLIENT SIDE
    import java.io.*;
    import java.net.*;
    public class XMLSocketC
              @SuppressWarnings("deprecation")
              public static void main(String[] args)
                   // Server: "localhost" here. And port to connect is 4545.
                   String host = "127.0.0.1";          
                   int port = 4545;
                   BufferedInputStream fileIn = null;
                   BufferedOutputStream out = null;
                   // File to be send over the socket.
                   File file = new File("c:/xampp/htdocs/thesis/sensorList.xml");
                   try
                        // InputStream to read the file
                        fileIn = new BufferedInputStream(new FileInputStream(file));
                   }catch(IOException eee)
                   {System.out.println("Problem");}
                   try
                             System.out.println("Establishing Socket Connection");
                             // Opening Socket
                             Socket clientSocket = new Socket(host, port);
                             System.out.println("Socket is clear and available.....");
                             // OutputStream to socket
                             out = new BufferedOutputStream(clientSocket.getOutputStream());
                             byte[] buffer = new byte[1024];
                             int numRead;
                             //Checking if bytes available to read to the buffer.
                             while( (numRead = fileIn.read(buffer)) >= 0)
                                  // Writes bytes to Output Stream from 0 to total number of bytes
                                  out.write(buffer, 0, numRead);
                             // Flush - send file
                             out.flush();
                             //=======================================
                             DataInputStream in = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
                             BufferedWriter outf = new BufferedWriter(new FileWriter("c:/xampp/htdocs/received_from_server.txt",true));
                             String str;
                             while(!(str = in.readLine()).equals("EOF")) {     
                                  System.out.println("client : Read line -> <" + str + ">");
                                  outf.write(str);//Write out a string to the file
                                  outf.newLine();//write a new line to the file (for better format)
                                  outf.flush();
                             //=======================================
                             // close OutputStream
                             out.close();
                             // close InputStrean
                             fileIn.close();
                             // close Socket
                             clientSocket.close();
                        }catch (IOException e)
                        {System.out.println("Exception.");}
         Could you please point where am I doing the stupid mistake, client to server is working properly, but the opposite direction is not.
    Thanks

  • Client/server socket based application

    hi does anyone have example of client/server socket based application using Spring and Maven
    where application do the following
    Client sends a request with a path to any file on the server
    „h Server reads the file and responds back with the content
    „h Client outputs the content to the console
    am trying to follow this
    http://www2.sys-con.com/itsg/virtualcd/java/archives/0205/dibella/index.html
    http://syntx.io/a-client-server-application-using-socket-programming-in-java/
    am using java 6

    i have attempt code but i wht to do the following
    client/server socket based application that will read the content of a file and stream the content of the file to the client. The client must simply output the content of the file to the console using System.out. The client must be able to run in a standalone mode (non-network mode) or in a remote mode.
    Additionally the client must be designed in a way that i can print the output to a console but must be interchangeable where if requirements change i can persist the response to file or persist the response to a database.
    /* Server.java*/
    ///ifgetBoolen= true then...
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.sql.*;
    public class Server
        static String array[][];
        // STEP 1 a1  
        // Server socket
        ServerSocket listener;
        // STEP 1 a2 Client connection
        Socket client;
        ObjectInputStream in;
        ObjectOutputStream out;
        public void createConnection() throws IOException
                System.out.println("\nSERVER >>> Waiting for connection.....");
                client = listener.accept();
                String IPAddress = "" + client.getInetAddress();
                DisplayMessage("SERVER >>> Connected to " + IPAddress.substring(1,IPAddress.length()));
          public void runServer()
            // Start listening for client connections
            // STEP 2
            try
                listener = new ServerSocket(12345, 10);
                createConnection();
                  // STEP 3
    //              processConnection();
            catch(IOException ioe)
                DisplayMessage("SERVER >>> Error trying to listen: " + ioe.getMessage());
        private void closeConnection()
            DisplayMessage("SERVER >>> Terminating connections");
            try
                if(out != null && in != null)
                      out.close();
                    in.close();
                    client.close();                
            catch(IOException ioe)
                DisplayMessage("SERVER >>> Closing connections");
        public static void define2DArray(ResultSet RS, int Size)
            try
                ResultSetMetaData RMSD = RS.getMetaData();
                DisplayMessage("SERVER >>> Requested arraySize: " + Size);
                if (RS.next())
                    array = new String[Size][RMSD.getColumnCount()];
                    for (int Row = 0; Row < Size; Row++)
                        for (int Col = 0; Col < RMSD.getColumnCount(); Col++)
                            array[Row][Col] = new String();
                            array[Row][Col] = RS.getString(Col+1);
                            DisplayMessage(array[Row][Col] + " ");
                        RS.next();
                else
                    array = new String[1][1];
                    array[0][0] = "#No Records";
            catch (Exception e)
                DisplayMessage("SERVER >>> Error in defining a 2DArray: " + e.getMessage());  
        public static void DisplayMessage(final String IncomingSMS)
            System.out.println(IncomingSMS);
    //client
    * @author
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    public class ClientSystem
        static Socket server;
        static ObjectOutputStream out;
        static ObjectInputStream in;
        static String Response[][];
        static boolean IsConnected = false;
        static int Num = 0;
        public static void connectToServer() throws IOException
            server = new Socket("127.0.0.1", 12345);
    //        server = new Socket("000.00.98.00", 12345);
            String IPAddress = "" + server.getInetAddress();
            DisplayMessage("\nCLIENT >>> Connected to " + IPAddress.substring(1,IPAddress.length()));
        public static void getStreams() throws IOException
            out = new ObjectOutputStream(server.getOutputStream());
            out.flush();
              in = new ObjectInputStream(server.getInputStream());
              IsConnected = true;
              DisplayMessage("CLIENT >>> Got I/O streams");  
        public static void runClient()
            try
                connectToServer();
                getStreams();
                  DisplayMessage("CLIENT >>> Connection successfull....\n");
                  DisplayMessage("CLIENT >>> Want to talk to server");
            catch (IOException ioe)
                System.out.print("."+Num);
                Num++;
        public static void closeConnection()
            try
                out.close();
                in.close();
                server.close();  
            catch(IOException error)
                DisplayMessage("CLIENT >>> Could not close connections");
        public static void Start()
            System.out.print("\nCLIENT >>> Attempting connection.....");
            try
                IsConnected = false;
                while (IsConnected == false)
                    runClient();
                    if (IsConnected == false)
                        Thread.sleep(100);
            catch (Exception e)
                DisplayMessage("CLIENT >>> Attempting connection.....");
        public static String sendSMS(String sms)
            Response = new String[0][0];
            try
                DisplayMessage("CLIENT >>> " + sms);
                out.writeObject(sms);
                out.flush();
                Response = (String[][])in.readObject();
                DisplayMessage("CLIENT >>> Waiting for server to respond...");
                for (int Row = 0; Row < Response.length; Row++)
                    System.out.printf( "_SERVER >>> \t");
                    for (int Col = 0; Col < Response[Row].length; Col++)
                        //DisplayMessage( "_SERVER >>> " + Response[Row][Col] + " ");
                        System.out.printf( "%s\t", Response[Row][Col]);
                    System.out.println();
                DisplayMessage("CLIENT >>> Query processed successfully....\n");
            catch(ClassNotFoundException cnfe)
                DisplayMessage("CLIENT >>> Class not found for casting received object");
            catch(IOException ioe)
                reConnect();          
            catch (Exception sqle)
                DisplayMessage("CLIENT >>> Error sending query ??? " + sqle.getMessage());
            return "transmission successfull";
        public static void reConnect()
            try
                DisplayMessage("CLIENT >>> Connection was lost. Trying to reconnect...");
                closeConnection();
                Thread.sleep(100);
                IsConnected = false;
                while (IsConnected == false)
                    runClient();
                    Thread.sleep(200);
            catch (Exception e)
                DisplayMessage("CLIENT >>> Error trying to Re-Connect...");
        public static void DisplayMessage(final String IncomingSms)
            System.out.println(IncomingSms);
        System.out.printf("Isms: %s", IncomingSms);  ///naah.
        public static String[][] getResponse()
            return Response;
        public static String getResponse(int row, int col)
            return Response[row][col];
    how can i do below using above code
    The program must be able to work in a non-networked mode. In this mode, the server and client must run in the same VM and must perform no networking, must not use loopback networking i.e: no “localhost” or “127.0.0.1”, and must not involve the serialization of any objects when communicating between the client and server components.
    The operating mode is selected using the single command line argument that is permitted.
    imust use a socket connection and define a protocol. networking must be entirely bypassed in the non-network mode.

  • Sockets will not close problem

    Hi all,
    We have a cient/server system that handles many connections using a dynamic pool of sockets (grows to a maximum and shrinks when not in use) spawned from a ServerSocket. The clients come and go with great frequency. They connect, pass some info, and disconnect again. The protocol implemented is that when the client wants to disconnect, it tells the server that it is finished using one of the fields in the message, and the server does the disconnect. The server side code that reacts to such a request to disconnect is as follows (btw, this is nicely indented for real, but can't get it to look right here):
    try
    logger.log(3, "CLOSE CLIENT INPUT STREAM");
    if(client_input != null)
    client_input.close();
    client_input = null;
    } catch(Exception se)
    logger.log(0, "Input Stream Close Error: "+ se);
    try
    logger.log(3, "CLOSE CLIENT OUTPUT STREAM");
    if(client_output != null)
    client_output.close();
    client_output = null;
    } catch(Exception se)
    logger.log(0, "Output Stream Close Error: "+ se);
    try
    logger.log(3, "CLOSE CLIENT SOCKET");
    if(clientSocket != null)
    clientSocket.close();
    clientSocket = null;
    } catch(Exception se)
    logger.log(0, "Client Socket Close Error: "+ se);
    finally
    if(clientSocket != null)
    try
    clientSocket.close();
    clientSocket = null;
    } catch(Exception ex)
    {} // nothing can be done
    By far most of the times this works perfectly. The problem is this. With some clients only (it's a public internet app and we get all kinds of clients, and it's not always the same client type where this happens - i.e. sometimes Win2000 using JDK 1.3.1, sometimes another) the server reports through the logger that the socket is closed and everthing appears OK, but it didn't really close the socket! Running netstat shows those connections as still ESTABLISHED. With the amount of re-connecting these clients do, it only takes 2 or 3 such "ill behaved clients" and we soon run up to our stated "maximum" number of sockets for the pool, and everything comes to a grinding halt!
    Searched the forums and only found one (very old) topic similar to this, with no answer.
    So the question is: IS THERE ANY WAY TO REALLY FORCE THE CLOSING OF A SOCKET AT THE SERVER END?
    Any thoughts appreciated.
    thanks,
    glitch

    Reposted all, with code tags
    Hi all,
    We have a cient/server system that handles many
    connections using a dynamic pool of sockets (grows to
    a maximum and shrinks when not in use) spawned from a
    ServerSocket. The clients come and go with great
    frequency. They connect, pass some info, and
    disconnect again. The protocol implemented is that
    when the client wants to disconnect, it tells the
    server that it is finished using one of the fields in
    the message, and the server does the disconnect. The
    server side code that reacts to such a request to
    disconnect is as follows (btw, this is nicely indented
    for real, but can't get it to look right here):
    try
    logger.log(3, "CLOSE CLIENT INPUT STREAM");
    if(client_input != null)
    client_input.close();
    client_input = null;
    } catch(Exception se)
    logger.log(0, "Input Stream Close Error: "+ se);
    try
    logger.log(3, "CLOSE CLIENT OUTPUT STREAM");
    if(client_output != null)
    client_output.close();
    client_output = null;
    } catch(Exception se)
    logger.log(0, "Output Stream Close Error: "+ se);
    try
    logger.log(3, "CLOSE CLIENT SOCKET");
    if(clientSocket != null)
    clientSocket.close();
    clientSocket = null;
    } catch(Exception se)
    logger.log(0, "Client Socket Close Error: "+
    r: "+ se);
    finally
    if(clientSocket != null)
    try
    clientSocket.close();
    clientSocket = null;
    } catch(Exception ex)
    {} // nothing can be done
    >
    By far most of the times this works perfectly. The
    problem is this. With some clients only (it's a
    public internet app and we get all kinds of clients,
    and it's not always the same client type where this
    happens - i.e. sometimes Win2000 using JDK 1.3.1,
    sometimes another) the server reports through the
    logger that the socket is closed and everthing appears
    OK, but it didn't really close the socket! Running
    netstat shows those connections as still ESTABLISHED.
    With the amount of re-connecting these clients do, it
    only takes 2 or 3 such "ill behaved clients" and we
    soon run up to our stated "maximum" number of sockets
    for the pool, and everything comes to a grinding
    halt!
    Searched the forums and only found one (very old)
    topic similar to this, with no answer.
    So the question is: IS THERE ANY WAY TO REALLY FORCE
    THE CLOSING OF A SOCKET AT THE SERVER END?
    Any thoughts appreciated.
    thanks,
    glitch

  • Unexpected Error - client$1 - pls help...

    Hi, I'm just started to set up my first app with Java Web Starter.
    I've solved al lot of problems and this one I can't find...
    Everything is going fine, he downloads the apps, start the installaten and then it stops with the error:
    Category: Unexpected Error
    client$1
    this is the code:
    import java.io.*;
    import java.net.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    public class client extends JFrame {
         private JTextField enter;
         private JTextArea display;
         ObjectOutputStream output;
         ObjectInputStream input;
         String message = "";
         public client()
              super( "client" );
              Container c = getContentPane();
              enter = new JTextField();
              enter.setEnabled (false);
              enter.addActionListener(
                   new ActionListener() {
                        public void actionPerformed (ActionEvent e )
                             sendData (e.getActionCommand() );
              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 {
                   String IP = JOptionPane.showInputDialog ("Geef IP of host in");
                   display.setText ( "Attempting to make connection\n" );
                   client = new Socket (
                        InetAddress.getByName ( IP ), 5222 );
                   display.append ("Connected to: " +
                        client.getInetAddress().getHostName() );
                   output = new ObjectOutputStream(
                        client.getOutputStream() );
                   output.flush();
                   input = new ObjectInputStream(
                        client.getInputStream() );
                   display.append ( "\nGot I/O streams\n" );
                   enter.setEnabled (true);
                   do {
                        try {
                             message = (String) input.readObject();
                             display.append ( "\n" + message);
                             display.setCaretPosition(
                                  display.getText().length() );
                        catch ( ClassNotFoundException cnfex ) {
                             display.append (
                                  "\nUnknown object type received.\n" );
                   }while ( !message.equals ( "SERVER>>> TERMINATE") );
                   display.append ( "closing connection.\n" );
                   input.close();
                   output.close();
                   client.close();
              catch ( EOFException eof ) {
                   System.out.println ( "Server terminated connection" );
              catch (IOException e ) {
                   e.printStackTrace();
         private void sendData (String s)
              try {
                   message = s;
                   output.writeObject ( "CLIENT>>> " + s );
                   output.flush();
                   display.append ( "\nCLIENT>>>" + s );
              catch (IOException cnfex ) {
                   display.append(
                        "\nError writing object" );
         public static void main ( String[] args )
              client app = new client();
              app.addWindowListener(
                   new WindowAdapter() {
                        public void windowClosing ( WindowEvent e )
                             System.exit(0);
              app.runclient();
    And is this the right command to make the rar?: jar cvf client.jar client.class
    After that command I added a signature.
    Is this about classpaths or anything?
    This is the webstart log:
    java.lang.NoClassDefFoundError: client$1
         at client.<init>(client.java:22)
         at client.main(client.java:102)
         at java.lang.reflect.Method.invoke(Native Method)
         at com.sun.javaws.Launcher.executeApplication(Unknown Source)
         at com.sun.javaws.Launcher.executeMainClass(Unknown Source)
         at com.sun.javaws.Launcher.continueLaunch(Unknown Source)
         at com.sun.javaws.Launcher.handleApplicationDesc(Unknown Source)
         at com.sun.javaws.Launcher.handleLaunchFile(Unknown Source)
         at com.sun.javaws.Launcher.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Greetz

    I found the solution. I used RealJ als editor and compiler and it seems he makes 3 files. client.class client$1.class and client$2.class. I thought these where backup classes. I included this 3 files in my JAR file and everything is going fine :)

  • How to handle multiple requests from single client??

    hi all
    I wrote a client server program to handle requests from client.I have 2 types of requests, one is to submit comments to the server other is to view comments on the server.I have tested the app and it works fine for either of them(independently) but they don't work both together i.e when i submit a comment and view it,it's stuck and when i close the program it gives SocketException :Connection reset.
    on client side:
    My request is just a string
    on the server side:
    I check the string and give the client what it wants.
    I want to know if there's any other way to send requests other than passing it as a string.
    I can post my code if needed.
    thanks,
    Sree

    Here is my client code,minimized it to the extent possible and it might give some compilation problems since i didn't include all the functions needed but i think you should be able to get an idea if i'm doing something wrong.
    Can give you my server code if needed.
    import java.io.BufferedReader;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import javax.swing.JButton;
    public class Test {
         JButton submit_button;
         JButton view_button;
         Socket client;
          JButton get_submit_button() {
                   if (submit_button == null) {
                        submit_button = new JButton();
                        submit_button.setText("Submit");
                        submit_button.addActionListener(new java.awt.event.ActionListener() {
                             public void actionPerformed(java.awt.event.ActionEvent e) {
                                  send_comments_to_server();
                   return submit_button;
               Socket check_client_connection(){
                   String host = "C001192097";     //server host name
                   if(client == null || client.isClosed()){
                    try {
                         client  = new Socket(host, 4321);
                    }catch (UnknownHostException exception){
                         System.err.println(host + ": unknown host.");
                    catch (IOException exception){
                         System.err.println("I/O error with " + host);
                   return client;
              void send_comments_to_server(){
                    try
                         Socket client = check_client_connection();
                         DataOutputStream output_stream = new DataOutputStream(client.getOutputStream());
                         BufferedReader stream_input = new BufferedReader(new InputStreamReader(client.getInputStream()));
                         String comment_report = "comments";
                         Comments comment = new Comments();
                         User_Data user_data = new User_Data(); //function that returns client details such as host name and stuff
                         String user_info = "User Name: "+user_data.user_name+" "+"Host Name: "+user_data.host_name+" "+"Domain Name: "+ user_data.domain_name;
                         comment.user_info = user_info;
                         comment.summary = comment_report;
                         comment.comments = "passing comments";
                         String report = user_info+" "+comment_report+" ";
                         output_stream.writeBytes(report+"\n");
    //                     output_stream.close();
    //                     stream_input.close();
    //                     client.close();
                    }catch(IOException e){
                         e.printStackTrace();
              void receive_comments_from_server(){
                   String line;
                   StringBuffer comments = new StringBuffer();
                   try
                         Socket client = check_client_connection();
                         DataOutputStream output_stream = new DataOutputStream(client.getOutputStream());
                         BufferedReader stream_input = new BufferedReader(new InputStreamReader(client.getInputStream()));
                         String msg = "view comments";
                         output_stream.writeBytes(msg);
                         System.out.println("waiting for response");
                             while((line = stream_input.readLine()) != null){
                                  comments.append(line);
                              System.out.println("Comments from server "+comments);     
                        } catch (IOException e) {
                             e.printStackTrace();
              JButton get_view_button() {
                   if (view_button == null) {
                        view_button = new JButton();
                        view_button.setText("View Comments");
                        view_button.addActionListener(new java.awt.event.ActionListener() {
                             public void actionPerformed(java.awt.event.ActionEvent e) {
                                  System.out.println("request sent");
                                  receive_comments_from_server();
                   return view_button;
    }thanks
    Sree

  • My client won't talk to my Server

    I'm trying to get my client to talk to my server and I keep getting an exception. Can anyone help me figure out what I did wrong?
    My Server
    import java.net.*;
    import java.io.*;
    public class Server
      public static void main(String[] args) throws IOException
        Socket client=null;
        PrintWriter pout=null;
        ServerSocket sock=null;
        try
          sock=new ServerSocket(5155);
          //now listen for connections
          while(true)
            client=sock.accept();
            //we have a connection
            pout=new PrintWriter(client.getOutputStream(), true);
            //write the Date to the socket
            pout.println(new java.util.Date().toString());
            pout.close();
            client.close();
        catch(IOException ioe)
          System.err.println(ioe);
        finally
          if(client!=null)
            client.close();
          if(sock!=null)
            sock.close();
    }My Client:
    import java.net.*;
    import java.io.*;
    public class Client
      public static void main(String[] args) throws IOException
        InputStream in=null;
        BufferedReader bin=null;
        Socket sock=null;
        try
          //make connection to socket
          sock=new Socket("127.0.0.1",5515);
          in=sock.getInputStream();
          bin=new BufferedReader(new InputStreamReader(in));
          String line;
          while((line=bin.readLine())!=null)
            System.out.println(line);
        catch(IOException ioe)
          System.err.println(ioe);
        finally
          if(sock!=null)
            sock.close();
    }

    A simple typo:
    sock=new ServerSocket(5155);
    sock=new Socket("127.0.0.1",5515);
    The port number must be the same.

  • Miultiple clients

    i have made a server and client socket .. I now want to make multiple clients access the same server.. Can anyone please help me as to what modifications should i make in the following code so that multiple clients can connect to the server and can talk to each other through text.......
    SERVER:
    import java.net.*;
    import java.io.*;
    public class server3
         public static void main(String args[])
                throws IOException
            Socket client_socket = null;
            ServerSocket serv_socket =null;
            PrintWriter out = null;
            BufferedReader in = null;
            try
            serv_socket = new ServerSocket(10052);
            catch(IOException e)
              System.out.println("Could not listen! port busy");
            System.out.println("Server ready,waiting for client: ");
            try
            client_socket = serv_socket.accept();
            catch(IOException e)
               System.out.println("Failed to accept client");
            try
            out = new PrintWriter(new PrintWriter(client_socket.getOutputStream()),true); // NOTE: here true flushes the outputstream
            in = new BufferedReader(new InputStreamReader(client_socket.getInputStream()));
            catch(IOException e)
                    System.out.println("Couldn't connect to client");
                    System.exit(1);
            String str;
            String str_out;
            str = in.readLine();
            while(!str.equalsIgnoreCase("close"))
             System.out.println("Message received:"+str);
             str_out = str.toString();
             str_out=str.toUpperCase();
             out.println(str_out);
             str = in.readLine();
            System.out.println("Client disconnected!");
            in.close();
            out.close();
         }CLIENT:
    import java.io.*;
    import java.net.*;
    public class client3
       public static void main(String args[])
                throws IOException
            Socket client_socket=null;
            PrintWriter out = null;
            BufferedReader in = null;
            BufferedReader user_in=null;
            try
            client_socket = new Socket("localhost",10052);
            int rp = client_socket.getPort(); // rp is the remote port to the which the client is  connected to the server!
            System.out.println("Client connected to server at port:"+rp);
            out = new PrintWriter(new PrintWriter(client_socket.getOutputStream()),true);
            in = new BufferedReader(new InputStreamReader(client_socket.getInputStream()));
            user_in = new BufferedReader(new InputStreamReader(System.in));
            catch(IOException e)
               System.out.println("UNknown Host");
               System.exit(1);
               String user;
               String str1 = new String();
            System.out.println("Enter Message: <write 'close' to end conversation>");
            user=user_in.readLine();
            while(!user.equalsIgnoreCase("close"))
            out.println(user);
            str1 = in.readLine();
            System.out.println("Message form <Server>:");
            System.out.println(str1);
            user=user_in.readLine();
            System.out.println("You have been disconnected fro server!");
            out.close();
            in.close();
    }Edited by: streetfi8er on Jul 2, 2009 7:23 PM

    i have tried to make a multiple client server ..... but i can't understand that how do i make the clients talk to each other...... how to i link their input and output streams? please help...
    Here's the revised code for it....
    import java.net.*;
    import java.io.*;
    public class server4
            public server4(int port)
            Socket client_socket = null;
            ServerSocket serv_socket =null;
            try
            serv_socket = new ServerSocket(port);
            catch(IOException e)
              System.out.println("Could not listen! port busy");
            System.out.println("Server ready,waiting for client: ");
            try
                while(true)
            client_socket = serv_socket.accept();
            server4Thread tp = new server4Thread(client_socket);
            serv_socket.close();
            catch(IOException e)
               System.out.println("Failed to accept client");
            public static void main(String args[])
                throws IOException
                new server4(9999);
            public class server4Thread extends Thread
            Socket client_socket =null;
            PrintWriter out = null;
            BufferedReader in = null;
                server4Thread(Socket client_socket)
            {   super("New THREAD");
                this.client_socket = client_socket;
                start();
            public void run()
              try
            out = new PrintWriter(new PrintWriter(client_socket.getOutputStream()),true); // NOTE: here true flushes the outputstream
            in = new BufferedReader(new InputStreamReader(client_socket.getInputStream()));
            catch(IOException e)
                    System.out.println("Couldn't connect to client");
                    System.exit(1);
              try
            String str;
            String str_out;
            str = in.readLine();
            while(!str.equalsIgnoreCase("close"))
             System.out.println("Message received:"+str);
             str_out = str.toString();
             str_out=str.toUpperCase();
             out.println(str_out);
            str = in.readLine();
              catch(IOException e)
                  System.out.println("Error in reading or writing");
            System.out.println("Client disconnected!");
            try
            in.close();
            out.close();
            catch(IOException e)
                System.out.println("Error in closing streams ");
    }

  • Making a threaded server client

    Alright I have to modify the following code to be a threaded-server and a threaded-client. I have no clue how to this and we weren't really taught how to do this, just kind of got thrown in. I'm not asking for the answer but for someone to point me in the direction of a program that is similiar so I can look at it and see what does what. Basically all I want is an example of a similiar program thanks.
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class DateServer
         public static void main(String[] args) throws IOException {
              Socket client = null;
              ServerSocket sock = null;
              try {
                   sock = new ServerSocket(6013);
                   // now listen for connections
                   while (true) {
                        client = sock.accept();
                        System.out.println("client = " + client);
                        // we have a connection
                        PrintWriter pout = new PrintWriter(client.getOutputStream(), true);
                        // Sleep a while
                        int aWhile = (int) (java.lang.Math.random()*5000);
                        java.lang.Thread.sleep (aWhile);
                        // write the Date to the socket
                        pout.println(new java.util.Date().toString());
                        pout.close();
                        client.close();
              catch (Exception err) {
                        System.err.println(err);
              finally {
                   if (sock != null)
                        sock.close();
                   if (client != null)
                        client.close();
    }Second part:
      import java.net.*;
       import java.io.*;
        public class DateClient
           public static void main(String[] args) throws IOException {
             InputStream in = null;
             BufferedReader bin = null;
             Socket sock = null;
             try {
                sock = new Socket("127.0.0.1",6013);
                in = sock.getInputStream();
                bin = new BufferedReader(new InputStreamReader(in));
                String line;
                while( (line = bin.readLine()) != null)
                   System.out.println(line);
                 catch (IOException ioe) {
                   System.err.println(ioe);
             finally {
                sock.close();
       }

    http://java.sun.com/docs/books/tutorial/networking/sockets/index.html
    That trail explains it all, including an easy to understand echo server/client pair.

Maybe you are looking for