0

I've been stuck about this problem and don't know how to fix it.

I try to create communication between server and client with java socket programming. I use the source code from this link for server and this link for client to create my application and divide it into 2 project packages (client and server). But for client side, I modify this source code to several Class because I want to add a library on this side.

The problem occur when i try to send a data from client to server with this modified sourcode. The socket from server always sent a message "Read failed" but it works properly (Can read) when i use the original source code.

This is the source code for server side (server package)

    package server;

/**
 *
 * @author IRVAN AHADI
 */
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;

import java.io.*;
import java.net.*;

class ClientWorker implements Runnable {
  private Socket client;
  private JTextArea textArea;

  ClientWorker(Socket client, JTextArea textArea) {
   this.client = client;
   this.textArea = textArea;   
  }

  public void run(){
    String line;
    BufferedReader in = null;
    PrintWriter out = null;
    try{
      in = new BufferedReader(new InputStreamReader(client.getInputStream()));
      out = new PrintWriter(client.getOutputStream(), true);
    } catch (IOException e) {
      System.out.println("in or out failed");
      System.exit(-1);
    }

    while(true){
      try{
        line = in.readLine();
//Send data back to client
         out.println(line);
         textArea.append(line);
       } catch (IOException e) {
         System.out.println("Read failed");
         System.exit(-1);
       }
    }
  }
}

class SocketThrdServer extends JFrame{

   JLabel label = new JLabel("Text received over socket:");
   JPanel panel;
   JTextArea textArea = new JTextArea();
   ServerSocket server = null;

   SocketThrdServer(){ //Begin Constructor
     panel = new JPanel();
     panel.setLayout(new BorderLayout());
     panel.setBackground(Color.white);
     getContentPane().add(panel);
     panel.add("North", label);
     panel.add("Center", textArea);
   } //End Constructor

  public void listenSocket(){
    try{
      server = new ServerSocket(4444);
      System.out.println("succes crate socket");
    } catch (IOException e) {
      System.out.println("Could not listen on port 4444");
      System.exit(-1);
    }
    while(true){
      ClientWorker w;
      try{
        w = new ClientWorker(server.accept(), textArea);
        Thread t = new Thread(w);
        t.start();
        System.out.println("succes accept socket");
      } catch (IOException e) {
        System.out.println("Accept failed: 4444");
        System.exit(-1);
      }
    }
  }

  protected void finalize(){
//Objects created in run method are finalized when 
//program terminates and thread exits
     try{
        server.close();
    } catch (IOException e) {
        System.out.println("Could not close socket");
        System.exit(-1);
    }
  }

  public static void main(String[] args){
        SocketThrdServer frame = new SocketThrdServer();
    frame.setTitle("Server Program");
        WindowListener l = new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                        System.exit(0);
                }
        };
        frame.addWindowListener(l);
        frame.pack();
        frame.setVisible(true);
        frame.listenSocket();
  }
}

This is the source code for client side (client package)

  1. Client.java

package client;

import java.io.*; 
import java.net.*;
public class Client{
Socket socket;
PrintWriter out = null;
BufferedReader in =  null;
String message = null;


        Client(){
                try{    
                    socket = new Socket("IRVANA-PC",4444);
                    out = new PrintWriter(socket.getOutputStream(),true);
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    System.out.println("Socket created and now connected to "+socket.getPort());
                }catch(UnknownHostException e){
                    System.out.println("Unknown host!");
                    System.exit(1);
                }catch(IOException e){
                    System.out.println("No I/O");
                    System.exit(1);
                }
        }

        Client(String host, int port){
                try{
                    socket = new Socket(host, port);
                    out = new PrintWriter(socket.getOutputStream());
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    System.out.println("Socket created and now connected to "+socket.getPort());
                }catch(UnknownHostException e){
                    System.out.println("Unknown host!");
                    System.exit(1);
                }catch(IOException e){
                    System.out.println("No I/O");
                    System.exit(1);
                }
        }

        public void sendData(String a){
                out.println(a);
        }

        public void getData(){
                try{
                    String line = in.readLine();
                    System.out.println("Text received :" + line);
                } catch (IOException e){
                    System.out.println("Read failed");
                    System.exit(1);
                }
        }

        public void disconnect(){
                try{
                    this.socket.close();
                }catch(IOException ioException){
                    ioException.printStackTrace();
                }
        }
    } 

2. Clientside.java (main class of client package)

package client;


import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.cmd.SigarCommandBase;
import org.hyperic.sigar.Sigar;


public class ClientSide {

public ClientSide(){

}

public static void main(String[] args) throws Exception{
    ClientSide client = new ClientSide();
    if ((args.length > 0) &&(args.length == 2))
    {

            int port = Integer.parseInt(args[1]);
            Client clientNetwork = new Client(args[0],port);
            System.out.println(clientNetwork.socket.getPort());
            String data = client.persentaseCPU();
            System.out.println(data);
            clientNetwork.sendData(data);                                

    }
    else{
        Client clientNetwork = new Client();
        String data = client.persentaseCPU();
        clientNetwork.sendData(data);
        }
    }

public String persentaseCPU() throws Exception{
    CpuNfo cpunfo = new CpuNfo();
    Sigar a = new Sigar();
    CpuPerc cpus = a.getCpuPerc();
    String percentage="idle "+CpuPerc.format(cpus.getIdle());
    return percentage;
}
}

I just wonderring why when I call clientNetwork.sendData(data); from Clientside.java it doesn't work, did I miss something? Did i create method sendData(String a) in Client.java correctly for send data through client socket?

Big thanks!

irvana
  • 343
  • 2
  • 5
  • 17
  • 1
    Please only post the portions of your code which are directly involved in the problem you're asking about- in this case that would be the parts of your program that directly deal with the socket/streams/writers and even then, it would be nice if you could narrow it down and tell us specifically which code you changed from the demo. – kaz Jun 15 '12 at 01:21
  • also "Read Failed" is your own error message. Please post the results of either `e.getMessage()` or `e.printStackTrace()` so that we can see what the actual error is. – kaz Jun 15 '12 at 01:28
  • Compare your approach to this working [example](http://stackoverflow.com/a/3245805/230513). – trashgod Jun 15 '12 at 01:42
  • Thanks @kaz , actually i just change client source code from demo into Client.java. I modify it into some methods, make the Client.java have more specific methods which not found in original source code demo. The error just "Read failed" and "Java Result: -1", nothing else, in my opinion i missing at sendData(String a) method in Client.java or streams in server side. Big sorry for my bad english and post... //i'm still searching for this solution.. :( – irvana Jun 15 '12 at 01:48
  • @irvana , your code `catch (IOException e) { System.out.println("Read failed"); System.exit(-1); }` is what's giving you those error messages. Replace them with `System.out.println(e.getMessage);` and `e.printStackTrace();` to see what is actually happening, then post those results here. – kaz Jun 15 '12 at 03:49

0 Answers0