First Very Simple Socket Program

Hello,
I am learning about Sockets and ServerSockets and how I can use the. I am trying to make the simplest server/client program possible just for my understanding before I go deper into it. I have written two programs. theserver.java and theclient.java the sere code looks like this....
import java.net.*;
import java.io.*;
import java.util.*;
public class theserver
  public static void main(String[] args)
  {   //  IOReader r = new IOReader();
        int prt = 3333;
        BufferedReader in;
         PrintWriter out;
        ServerSocket serverSocket;
        Socket clientSocket = null;
try{
serverSocket = new ServerSocket(prt);  // creates the socket looking on prt (3333)
System.out.println("The Server is now running...");
while(true)
    clientSocket = serverSocket.accept(); // accepts the connenction
    clientSocket.getKeepAlive(); // keeps the connection alive
    out = new PrintWriter(clientSocket.getOutputStream(),true);
    in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
     if(in.ready())
     System.out.println(in.readLine()); // print it
catch (IOException e) {
    System.out.println("Accept failed:"+prt);
}and the client looks like this
import java.net.*;
import java.io.*;
public class theclient
public static void main(String[] args)
    BufferedReader in;
    PrintWriter out;
    IOReader r = new IOReader();
    PrintWriter sender;
    Socket sock;
  try{
    sock = new Socket("linuxcomp",3333);  // creates a new connection with the server.
    sock.setKeepAlive(true); // keeps the connection alive
    System.out.println("Socket is connected"); // confirms socket is connected.
    System.out.println("Please enter a String");
     String bob = r.readS();
      out = new PrintWriter(sock.getOutputStream(),true);
    out.print(bob); // write bob to the server
  catch(IOException e)
       System.out.println("The socket is now disconnected..");
}If you notice in the code I use a class I made called IOReader. All that class is, is a buffered reader for my System.in. (just makes it easier for me)
Ok now for my question:
When I run this program I run the server first then the client. I type "hello" into my system.in but on my server side, it prints "null" I can't figure out what I am doing wrong, if I am not converting correctly, or if the message is not ever being sent. I tried putting a while(in.read()) { System.out.println("whatever") } it never reaches a point where in.ready() == true. Kinda of agrivating. Because I am very new to sockets, I wanna aks if there is somthing wrong with my code, or if I am going about this process completely wrong. Thank you to how ever helps me,
Cobbweb

An example of Creating a Client Socket (Java socket programming tutorial)
try {
        InetAddress addr = InetAddress.getByName("hotdir.biz");
        int port = 80;
        // This constructor will block until the connection succeeds
        Socket socket = new Socket(addr, port);
    } catch (UnknownHostException e) {
    } catch (IOException e) {
    // Create a socket with a timeout
    try {
        InetAddress addr = InetAddress.getByName("hotdir.biz");
        int port = 80;
        SocketAddress sockaddr = new InetSocketAddress(addr, port);
        // Create an unbound socket
        Socket sock = new Socket();
        // This method will block no more than timeoutMs.
        // If the timeout occurs, SocketTimeoutException is thrown.
        int timeoutMs = 2000;   // 2 seconds
        sock.connect(sockaddr, timeoutMs);
    } catch (UnknownHostException e) {
    } catch (SocketTimeoutException e) {
    } catch (IOException e) {
    }See socket tutorial here http://www.developerzone.biz/index.php?option=com_content&task=view&id=94&Itemid=36

Similar Messages

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

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

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

  • [New] Help with a VERY simple asterisk program.

    Alright...I feel like a complete idiot asking this question..but I'm having such trouble writing this program. The program description is here:
    Write a Java application using two for loops to produce the following pattern of asterisks.
    I guess I'm really bad at algorithms yeah? Haha...well, any help would be very much appreciated.

    Hi,
    I don't think you don't need to look through any C programming books.
    When you have a problem like this, do some thinking about what methods you need to use and what the general structure of the program will be.
    You need to print asterisks out to the screen... so you'll need:
    System.out.println
    System.out.printAnd you already know that you need two loops.
    Now you can ask yourself how you might use the print statements with two loops in order to design a basic structure for the program.
    You have 8 lines, so you might want a loop that runs through 8 times, one of the lines printed each time.
    Within this loop, you need another loop that prints out *'s. This loop could run once for each asterisk, but because there is a different number of asterisks on each line, the number of times this loop runs would be variable.
    So a basic structure:
    //loop1 that runs 8 times
        //loop2 that runs once for each *
            print one star
        //end loop2
    //end loop1The key now is to recognise the difference between print and println. I don't know if you alread know, but System.out.print will print a string without creating a new line at the end, and println will create a new line at the end of the printed string.
    Hope that helps. If you have any other problems, post specific questions along with the code you've written and are having trouble with.

  • Error when running a very simple java program

    java.lang.NoClassDefFoundError: HelloWorldApp
    Exception in thread "main"
    Tool completed successfully
    I am getting the above error. I just downloaded java standard edition 1.4 sdk. I compiled the program with no errors. But when I run it . I get the above error. Is it something related to finding the package java.lang?
    Please let me know.
    Thanks.

    I have the same problem but in a different way. I download/installed jdk1.4 and J2me. I was able to run j2me without any problem following their tutorial.
    I set my config.sys to:
    PATH=C:\j2sdk1.4.0\bin;C:\j2me\j2me_cldc\bin;C:\j2me\midp1.0.3fcs\bin;
    I did compile and ran couple of programs with no problems at all, for some reason some of them give me error ex: Exception in thread "main" java.lang.NoClassDefFoundError: NamofFile
    I read couple of posting about setting the CLASSPATH, is that maybe the source of the problem if so how I can do so given that I�m using win2000. Any Ideas !!!

  • Simple Socket Program error

    I got no no output in either the server/client terminal for the following pair of server/client code. Can anyone please point where have I made a basic mistake in the flow of things...
    Server Code:-
    import java.io.*;
    import java.net.*;
    public class TCP_File_Server
         public static void main(String st[])
              try
                   String msg="start";
                   ServerSocket listen_socket=new ServerSocket(7001);
                   while(true)
                        Socket conn_socket=listen_socket.accept();
                        BufferedReader in_client=new BufferedReader(new InputStreamReader(conn_socket.getInputStream()));
                        DataOutputStream out_server=new DataOutputStream(conn_socket.getOutputStream());
                        msg=in_client.readLine();
                        System.out.println(msg);
                        out_server.writeBytes("Wassup ?!");
                        conn_socket.close();                    
              catch(IOException e)
                   System.out.println(e.toString());
    Client Code:
    import java.io.*;
    import java.net.*;
    public class TCP_File_Client
         public static void main(String st[])
              try
                   if(st.length==1)
                   String path=st[0];
                   Socket clientSocket=new Socket("localhost",7001);
                   DataOutputStream out_server=new DataOutputStream(clientSocket.getOutputStream());
                   BufferedReader in_server=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                   out_server.writeBytes(path);     
                   System.out.println(in_server.readLine());
                   clientSocket.close();
              catch(IOException e)
                   System.out.println(e.toString());
    }

    Have my concepts of Streams thorough bro...! Socket transmission always takes place by byte stream... and even if i use bufferedreader, it has an underlying inputstreamreader which converts byte to char stream, so shouldn't be a problem... :)
    Guaranteed to be a problem unless you can guarantee that the bytes you wrote will turn into the characters you expect via the charset used by that implicit InputStreamReader.

  • Need help getting a very simple RMI program running

    I've been pulling my hair out trying to get RMI running on windows. I decided to do a verbatim copy of a tutorial to see if it would work, well it didn't. Here is the sample code:
    //HelloInterface.java - located in dir c:\java
    import java.rmi.*;
    public interface HelloInterface extends Remote {
    public String say() throws RemoteException;
    //Hello.java - located in c:\java
    import java.rmi.*;
    import java.rmi.server.*;
    public class Hello extends UnicastRemoteObject implements HelloInterface {
    private String message;
    public Hello (String msg) throws RemoteException {
    message = msg;
    public String say() throws RemoteException {
    return message;
    //HelloServer.java - located in c:\java
    import java.rmi.*;
    import java.rmi.Naming;
    public class HelloServer{
    public static void main (String[] argv) {
    try {
    Naming.rebind ("Hello", new Hello ("Hello, world!"));
    System.out.println ("Hello Server is ready.");
    } catch (Exception e) {
    System.out.println ("Hello Server failed: " + e);
    Then I open a command prompt and go to c:\java and type:
    C:\java>javac HelloInterface.java
    C:\java>javac Hello.java
    C:\java>rmic Hello
    C:\java>javac HelloServer.java
    I then open a second command prompt and navigate to c:\registry to (to avoid being in the same directory as the stub files) and type:
    C:\register>C:\j2sdk1.4.2_03\bin\rmiregistry
    In the original command prompt, I then run HelloServer. I've tried running it a 100 different ways and always get the same error:
    Hello Server failed: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
    java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
    java.lang.ClassNotFoundException: Hello_Stub
    I've tried just running it as:
    java HelloServer
    java -classpath . HelloServer
    C:\java>java -Djava.rmi.server.codebase=http://localhost -classpath . HelloServer
    C:\java>java -Djava.security.policy=..\policy.all -Djava.rmi.server.codebase=http://localhost -classpath . HelloServer
    Where policy.all is:
    grant {
         permission java.security.AllPermission;
    And pretty much just about every combination of the above that you can think of.

    //HelloInterface.java - located in dir c:\java
    import java.rmi.*;
    public interface HelloInterface extends Remote {
      public String say() throws RemoteException;
    }//Hello.java - located in c:\java
    import java.rmi.*;
    import java.rmi.server.*;
    public class Hello extends UnicastRemoteObject implements HelloInterface {
      private String message;
      public Hello (String msg) throws RemoteException {
        message = msg;
      public String say() throws RemoteException {
        return message;
    }//HelloServer.java - located in c:\java
    import java.rmi.*;
    import java.rmi.Naming;
    public class HelloServer{
      public static void main (String[] argv) {
        try {
          Naming.rebind ("Hello", new Hello ("Hello, world!"));
          System.out.println ("Hello Server is ready.");
        } catch (Exception e) {
          System.out.println ("Hello Server failed: " + e);
    }I'm not sure what you are saying about the CLASSPATH. I thought rmiregistry had to be ran in a different directory than the stub files and that the stubs shouldn't be in the CLASSPATH of the terminal launching rmiregistry.
    The HelloServer is being ran with the -classpath option set to "." and the stubs are in the same directory.

  • Help with a simple Java program

    I'm making a sort of very simple quiz program with Java. I've got everything working on the input/output side of things, and I'm looking to just fancy everything up a little bit. This program is extremely simple, and is just being run through the Windows command prompt. I was wondering how exactly to go about making it to where the quiz taker was forced to hit the enter key after answering the question and getting feedback. Right now, once the question is answered the next question is immediately asked, and it looks kind of tacky. Thanks in advance for your help.

    Hmm.. thats not quite what I was looking for, I don't think. Here's an example of my program.
    class P1 {
    public static void main(String args[]) {
    boolean Correct;
    char Selection;
    int number;
    Correct = false;
    System.out.println("Welcome to Trivia!\n");
    System.out.println("Who was the first UF to win the Heisman Trophy?\n");
    System.out.print("A) Danny Wuerffel\nB) Steve Spurrier\nC) Emmit Smith\n");
    Selection = UserInput.readChar();
    if(Selection == 'B' | Selection == 'b')
    Correct = true;
    if(Correct == true)
    System.out.println("\nYou have entered the correct response.");
    else
    System.out.println("\nYou missed it, better luck next time.");
    System.out.println("(\nHit enter for the next question...");
    System.in.readLine();
    Correct = false;
    System.out.println("\nWhat year did UF win the NCAA Football National Championship?\n");
    number = UserInput.readInt();
    if(number == 1996)
    Correct = true;
    if(Correct == true)
    System.out.println("\nYou have entered the correct response.");
    else
    System.out.println("\nYou missed it, better luck next time.");
    Correct = false;
    System.out.println("\nWho is the President of the University of Florida?\n");
    System.out.println("A) Bernie Machen\nB) John Lombardi\nC) Stephen C. O'Connell\n");
    Selection = UserInput.readChar();
    if(Selection == 'A' | Selection == 'a')
    Correct = true;
    if(Correct == true)
    System.out.println("\nYou have entered the correct response.");
    else
    System.out.println("\nYou missed it, better luck next time.");
    }

  • Weblogic error while deplying a simple servlet program

    Hi This is a very simple servlet program.
    I am trying to deploy it on the weblogic server but i get this error as follow
    Unable to access the selected application.
    *javax.enterprise.deploy.spi.exceptions.InvalidModuleException: [J2EE Deployment SPI:260105]Failed to create*
    DDBeanRoot for application, 'E:\AqanTech\WebApp1\myApp.war'.
    I have checked everything, right from my code to my web.xml file. I have used a build.bat file to build my war file.
    PLEASE HELP ME TO SOLVE THIS HUGE PROBLEM OF MINE ?
    Thanks,
    Shoeb

    Hi,
    The J2EE Error code siply suggest that there is something wrong in your Deployment Descriptors...
    Can u please post the XML files available inside your "WEB-INF" directory?
    Thanks
    Jay SenSharma
    http://jaysensharma.wordpress.com (WebLogic Wonders Are Here)

  • GetRuntime can NOT exec very simple C executable

    Dear all,
    I compiled the following very simple C program as echo.exe in windows, now I want to use
    Process process = Runtime.getRuntime().exec("echo");
    to output all results from echo.exe to a JTextArea.
    So I created an
    inputStream = new BufferedInputStream(process.getInputStream());
    and then use a thread to detect any outputs from the thread:
    // inside run
    while (inputStream.available()==0) {
         Thread.currentThread().sleep(100);
    byte[] bytes = new byte[inputStream.available()];
    inputStream.read(bytes);
    /* output is a JTextArea */
    output.setText(new String(bytes));
    Now the problem is: it even can not print out "Prompt>", until I type "quit" to exit the program, and then print out everything save from the start.
    I tested again and again by modifing the C program and noticed that the problem here is gets( line ) - seems it blocks for ever -> if I do not use this line, everything is ok. I do not know why it even does not execute printf("\nPrompt> "); going to gets(line); ?
    Anything wrong here? Any suggestions?
    Note: Just ignore any inputs from user now, I only needs to display "Prompt>" in JTextArea, since this is my major problem.
    Many thanks!
    /* echo.c*/
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    int main()
      char line[1024];
      while(1) {
        printf("\nPrompt> " ) ;
        gets( line ) ;
        if(strcmp(line,"quit") == 0) {
          break;
        else {
         printf("%s", line);
      return 0;
    }

    I haven't tried this but it should work. The output stream
    should be obtained if you want to break out of the gets() statement.
    when you write to the stream always include the '\n' character.
    Process process = Runtime.getRuntime().exec("echo");
    inputStream = new BufferedInputStream(process.getInputStream());
    // inside run
    String str = inputStream.readLine();
    output.setText(str);
    PrintWriter out = new PrintWriter(process.getOutputStream());        
    out.println("quit\n");  
    out.flush();
    out.close();
    out = null;
    /* echo.c*/
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    int main()
      char line[1024]; 
      while(1)
        printf("Prompt>\n" );   
        gets( line ) ;   
        if(strcmp(line,"quit") == 0)
          break;   
        else
          printf("%s", line);   
      return 0;

  • Very Simple Problem-- Need help in method selection process

    Hello,
    It's difficult to explain the background of the program I am making-- but I am stuck at a very simple problem, that I can only solve with a very long block of if statements:
    I have 3 possible numbers-- 1, 2, or 3.
    Imagine two numbers are already taken-- say 1 and 2. I want a variable to set itself to the number that's not taken (3).
    So, again: If two numbers were taken say 2 or 3-- I want the variable to be sent to the other one that isn't taken-- 1.
    Thank you for your help,
    Evan.

    Actually, I'll just tell you the context of the program-- here is what I have so far:
    This program is meant to simulate Monty Hall Problem:
    http://en.wikipedia.org/wiki/Monty_Hall_problem
    The program sets up an array of three possible values. Each one of those values represents a door with either a goat or a car behind it. It then randomly sets one of those values to 1 (in order to represent a car as per the Monty Hall problem), and 0's represent goats.
    The user, which is simulated by the program (does not involve actual interaction), chooses a door initially.
    The game show hosts then reveals a door that is not the users initial choice, but IS a goat ( an array value of 0).
    For example if the array was [0][0][1]
    The user could pick door one (array position 0). Which is a goat.
    The game show host then reveals a goat that is not the users choice-- which would be array position 1.
    After the game show host reveals the goat-- I want the user to always switch his decision to the only other remaining door that was not his first choice.
    Then I wanted the computer to test to see if his final choice is the one with a car. And to tally up the amount of times he got it right.
    --Sorry that was long winded:
    import TerminalIO.*;//imports TerminalIO package for system.out.println
    import java.util.*;//import java.util for random
    public class Monty_Problem
         int doors[]= {0,0,0};
         Random rand= new Random();
         double wins,totals=0;
         public void carAssignment()
              int car_door= rand.nextInt(3);
              doors[car_door]=1;
         public int judgesChoice(int judgeDoor, int initialChoice)
              if(judgeDoor != initialChoice && doors[judgeDoor]!=1)
                   return judgeDoor;
              else
                   return judgesChoice(rand.nextInt(3), initialChoice); //infinite loop right here that I cannot remedy.  I want the program to have the judge pick a location that is not occupied by a  '1' and is not the user's choice. 
         public void gamePlaySwitches()
              int initialChoice= rand.nextInt(3);
              int judgeDoor = 0;
              int secondChoice= 0;
              judgeDoor= judgesChoice(rand.nextInt(3), initialChoice);
              //This part is meant to have the user switch choices from his initial choice
                   // to the only other choice that hasn't been revealed by the judge. 
              while(secondChoice == initialChoice || secondChoice== judgeDoor)
                   secondChoice++;
              if(doors[secondChoice]==1)
                   wins++;
                   totals++;
              else
                   totals++;          
         public static void main(String [] args)//creates the main menu
              Monty_Problem a= new Monty_Problem();
              int games=0;
              while(games!=100)
                        a.carAssignment();
                        a.gamePlaySwitches();
                        games++;
              System.out.println(a.wins/a.totals);
    }Edited by: EvanD on Jan 11, 2008 4:17 PM

  • Network and socket programming in python

    i want to learn network and socket programming but i would like to do this in python.Reason behind this is that python is very simple and the only language i know . 
    anybody can suggest me which book should i pick.
    the book should have following specification--
    1)not tedious to follow
    2)lots of example
    3)starts with some networking stuff and then get into codes
    thanks in advance with regards.

    hmm. well, your requirements are almost contradictory.
    Not sure about books, except maybe dusty's.
    Most python books cover at least some network programming (unless the book is topic specific).
    I use lots of python-twisted at work. I mean ALOT. I wouldn't recommend it to someone looking for non-tedious though! I also like gevent/eventlet (esp. the async socket wrappers).
    EDIT: Wow. My post wasn't really helpful at all. Sorry!
    Last edited by cactus (2010-09-04 09:16:54)

  • How to create desktop application for simple server program using netbeans?

    Hi,can anyone help me on this one??
    I'm am very new to java,and I already trying different example program to create desktop applications
    for simple server program but it's not working.
    This is the main program for the simple server.
    import java.io.*;
    import java.net.*;
    public class Server {
    * @param args the command line arguments
    public static void main(String[] args) {
    try{
    ServerSocket serverSocket = new ServerSocket(4488);
    System.out.println("Server is waiting for an incoming connection on port 4488");
    Socket socket = serverSocket.accept();
    System.out.println(socket.getInetAddress() + "connected");
    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null){
    out.println(inputLine);
    System.out.println("Connection will be cut");
    out.close();
    in.close();
    socket.close();
    serverSocket.close();
    }catch(IOException e){
    e.printStackTrace();
    // TODO code application logic here
    }

    and this is the Main Processing :
    import java.awt.*;
    import java.awt.event.*;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    import java.text.*;
    import java.util.*;
    import java.net.*;
    import java.io.*;
    public class MainProcessing {
    private static final long serialVersionUID = 1L;
    static private boolean isApplet_ = true;
    static private InetAddress argIp_ = null;
    static private int argPort_ = 0;
    public TCPIP TCPIP_ = null;
    private InetAddress ip_ = null;
    private int port_ = 10001;
    static private boolean conectFlag = false;
    private BufferedWriter bw;
    FileOutputStream fos;
    OutputStreamWriter osw;
    public int[] current = new int[400];
    public int[] volt = new int[400];
    public int[] revolution = new int[400];
    public void init() {
    public void start() {
    if (isApplet_) {
    try {
    ip_ = InetAddress.getByName(getCodeBase().getHost());
    } catch (UnknownHostException e) {
    } else {
    ip_ = argIp_;
    if (argPort_ != 0) {
    port_ = argPort_;
    // IP&#12450;&#12489;&#12524;&#12473;&#12364;&#19981;&#26126;&#12394;&#12425;&#20309;&#12418;&#12375;&#12394;&#12356;
    if (ip_ != null) {
    // &#12467;&#12493;&#12463;&#12471;&#12519;&#12531;&#12364;&#25104;&#31435;&#12375;&#12390;&#12356;&#12394;&#12356;&#12394;&#12425;&#12289;&#25509;&#32154;
    if (TCPIP_ == null) {
    TCPIP_ = new TCPIP(ip_, port_);
    if (TCPIP_.getSocket_() == null) {
    System.out.println("&#12511;&#12473;&#65297;");
    // &#12456;&#12521;&#12540;&#12513;&#12483;&#12475;&#12540;&#12472;&#12434;&#34920;&#31034;
    return;
    if (TCPIP_ == null) {
    System.out.println("&#12511;&#12473;&#65298;");
    return;
    System.out.println("&#25104;&#21151;");
    conectFlag = true;
    try {
    TCPIP_.sendF();
    } catch (IOException ex) {
    Logger.getLogger(MainProcessing.class.getName()).log(Level.SEVERE, null, ex);
    System.out.println("" + conectFlag);
    return;
    public void receive() {
    try {
    // Calendar cal1 = Calendar.getInstance(); //(1)&#12458;&#12502;&#12472;&#12455;&#12463;&#12488;&#12398;&#29983;&#25104;
    // int year = cal1.get(Calendar.YEAR); //(2)&#29694;&#22312;&#12398;&#24180;&#12434;&#21462;&#24471;
    // int month = cal1.get(Calendar.MONTH) + 1; //(3)&#29694;&#22312;&#12398;&#26376;&#12434;&#21462;&#24471;
    // int day = cal1.get(Calendar.DATE); //(4)&#29694;&#22312;&#12398;&#26085;&#12434;&#21462;&#24471;
    // int hour = cal1.get(Calendar.HOUR_OF_DAY); //(5)&#29694;&#22312;&#12398;&#26178;&#12434;&#21462;&#24471;
    // int min = cal1.get(Calendar.MINUTE); //(6)&#29694;&#22312;&#12398;&#20998;&#12434;&#21462;&#24471;
    // int sec = cal1.get(Calendar.SECOND); //(7)&#29694;&#22312;&#12398;&#31186;&#12434;&#21462;&#24471;
    byte[] rev = TCPIP_.receive();
    // System.out.println("&#21463;&#20449;");
    if (rev != null) {
    byte[] Change = new byte[1];
    int j = 0;
    for (int i = 0; i < 1200; i++) {
    Change[0] = rev;
    current[j] = decimalChange(Change);
    i++;
    Change[0] = rev[i];
    volt[j] = decimalChange(Change);
    i++;
    Change[0] = rev[i];
    revolution[j] = decimalChange(Change);
    } catch (NullPointerException e) {
    public int decimalChange(byte[] byteData) {
    int bit0, bit1, bit2, bit3, bit4, bit5, bit6, bit7;
    int bit = 0;
    for (int i = 0; i < 8; i++) {
    int a = (byteData[0] >> i) & 1;
    System.out.print(a);
    System.out.println();
    return 1;
    public void destroy() {
    // &#20999;&#26029;
    if (TCPIP_ != null) {
    TCPIP_.disconnect();
    if (TCPIP_.getSocket_() != null) {
    try {
    System.out.println("\ndisconnect:" + TCPIP_.getSocket_().getInetAddress().getHostAddress() + " " + TCPIP_.getSocket_().getPort());
    } catch (Exception e) {
    TCPIP_ = null;
    public boolean conect(int IP) {
    conectFlag = false;
    String address = "192.168.1." + IP;
    System.out.println(address);
    try {
    argIp_ = InetAddress.getByName(address);
    } catch (UnknownHostException e) {
    // xp.init();
    isApplet_ = false;
    start();
    return (conectFlag);
    public void send(String command, int value, int sendData[][], int i) {
    int j = 0;
    Integer value_ = new Integer(value);
    byte values = value_.byteValue();
    Integer progNum = new Integer(i);
    byte progNums = progNum.byteValue();
    try {
    TCPIP_.send(command, values, progNums);
    for (j = 1; j <= i; j++) {
    Integer time = new Integer(sendData[j][0]);
    byte times = time.byteValue();
    Integer power = new Integer(sendData[j][1]);
    byte powers = power.byteValue();
    TCPIP_.send(times, powers);
    TCPIP_.flush();
    } catch (IOException ex) {
    Logger.getLogger(MainProcessing.class.getName()).log(Level.SEVERE, null, ex);
    public void file(String name) {
    ublic void fileclose(String name, String command, int value, int sendData[][], int i) {
    try {
    fos = new FileOutputStream("" + name + ".csv");
    osw = new OutputStreamWriter(fos, "MS932");
    bw = new BufferedWriter(osw);
    String msg = "" + command + "," + value + "";
    bw.write(msg);
    bw.newLine();
    for (int j = 1; j <= i; j++) {
    msg = "" + j + "," + sendData[i][0] + "," + sendData[i][1];
    bw.write(msg);
    bw.newLine();
    bw.close();
    } catch (IOException ex) {
    Logger.getLogger(MainProcessing.class.getName()).log(Level.SEVERE, null, ex);

  • Help on Server Socket Programming??????

    hello Friends,
    I need your help on following:
    I am the only person working on this project and the company wants me to prepare a infrastructure of this project and I should also give a demo of this project to my seniors. I will breif you up with my project:
    1. There is this gif image of distillation column. i will be publishing it using JApplet or Applet.
    2. This Image must be seen on internet.
    3. On the circle of these Image the user will click(In all there are five circles, called as controllers)and a dialog box should open thru which user will input the float values(I am using the JOptionPane class to open this dialog box).
    4. The inputed values will the be given to the C program which is the simulator for distillation column.
    5. The C program will generate the output through iterations(Code entirely in C), the output of each program will then be poped up to over the image beside the respective controlled or under the respective controller but definetely over the same gif file.
    6. The number of iteration will depend on how fast the C program converges the inputer parameters. And each output must be show over the gif image and when the final iteration value will appear it should remain on the image until some new value is inputted by the user again by clicking on any of the circle.
    The proposed theory to do this project accoding to me is as follows:
    1. Since each value must be thrown to the user. I beleive this is a real time project. So I decided to use Client Server Networking technology provided by java.
    2. Then I figured out that in this project there should be 2 clients One is the GUI which is the Image screen to receive the input from the user and to show the output to the user. Second client is a java program sitting behind the server which will receive this input data from user and it will have an NATIVE method through which all this input will be given to the C simulator program.
    3. The middle bridge between these two clients will be a server. Which will just pass the data to and fro from both the clients.
    3. The C program will perform iterations using these input values from second client. This C program will then give each iterations output to the Java program using JNI technology. This second client then sends this output value to the GUI clients through server.
    Well another very important thing, I am inexperience in the field of software so I had to do a lot of R&D and this is what I found out. Frankly I am really not sure whether this is the right path to approach to this project or there is some other correct and realistic way than this? Well friends i would certainly request you if you can suggest some other simple or rather correct path or else if this is the right path then would you please suggest me the possible hiches or perticular points where I should concentrate more.
    Well i am eagerly waiting for your reply.

    Since you are publishing your results on the net , it will be a better idea to use JSP?Servlet/Beans architecture instead of swing
    I will propose a architecture as follows:
    Client : Standard Browsers, IE and NS
    Middle Tier: Java Webserver/Application Server
    This will depend on your budget. If u have a fat allowance go for weblogic/websphere . If u are operationg on shoe string budget try for apache , etc
    In the server tier code your application in the follwing architecture
    JSP for presentation: Distillation towers picture, input boxes .. etc
    Servlets for business logic invocation and routing requests: Your JSP submits input values to servlets, which does the processing using Java Bean Components. Since you have a lot of Logic written in C I would suggest to encapsulate these in JavaBean components using JNI technology and reuse the code.
    After processing the servlet again forwards the response to another JSP for output
    Advantages:
    1.Your clients can be thin as most of the processing is done at the server
    2. Thread Management is taken care of by your webserver, which otherwise would be a headache
    3. Writing this through low level socket programming will be much more difficult as you will write your own protocol for communication this will be error prone and not scalable
    If you still decide to go for traditional client server programming using swing, use RMI for communication as I insist that socket programming is very very cumbersome...using your own protocols
    hope this helps
    Shubhrajit

  • Desktop to socket programming conversion problem?

    i have a Online desktop application.
    i want to convert in Socket programming for Efficiency and Quick response.
    i successfully connect client to server and server to client its work well.
    now problem is that i had in application different type of objects , Database quires results, some Business class and other needed class.
    how i pass these thinks to server to client and vice versa and distinguish them?

    I am very THANK Full for your Efforts
    i locked my xml file succssfuly; but i still got same exception
    locking a file code
    Initializing streams
    try {
                is = new ObjectInputStream(clientSocket.getInputStream());
                os = new ObjectOutputStream(clientSocket.getOutputStream());
               fs = new FileOutputStream("first.xml");
                BufferedOutputStream br = new BufferedOutputStream(fs);
                xml = new XMLEncoder(br);
            } catch (IOException e) {
                System.out.println(e);
    Locking a file it display file is locked
         System.out.println("Trying to lock locked..");
          fl = fs.getChannel().tryLock();
          System.out.println("File locked..");
          xml.writeObject(ud);
          xml.flush();
          fl.release();
          System.out.println("lock released...");    
          fl.release();
          is.close();
          os.close();
          xml.close();
          clientSocket.close();       

  • Video stutter in very simple video project

    My very simple 20 minute travel video, made in iMovie 4.0.1, with less than 10 transitions and extracted audio clips, freezes, stutters, and is impossible to edit. It's my first project in this version of iMovie. I got the program, along with Quicktime 7.11, when I upgraded to OSX 10.3.9.
    I've posted before, and added RAM as recommended. Now my computer meets the specs for iMovie 4. It's used for very little else. No external hard drive, no bookmarks, and very few audio clips and transitions. Also tried downloading the updated Quicktime 7.13. Same problem.
    When I remove audio clips, stuttering is almost all gone.
    I would think this program would be able to handle such a simple project.
    Any advice you might have would be appreciated. Should I go back to earlier versions of the programs? Operating system? If so, how do I do that?

    Using old hardware with iMovie is a crapshoot, especially with QT 7. On my G4, I had to downgrade to QT 6.5.2 as someone else suggested. I also ran into the problem you did in trying to downgrade. Here is the solution that got me by:
    1. Download Pacifist (http://versiontracker.com/dyn/moreinfo/macosx/12743). This will allow you to bypass the downgrade error you received in running the Reinstaller.
    2. First run the QT 7.0.1 Reinstaller (this is where Pacifist came in handy).
    NOTE: It may be hard to finder this Reinstaller. If you have problems, first try step 3 below using Pacifist, but if that does not work, I can find a way to get you the 7.0.1 Reinstaller.
    3. Next run the QT 6.5.2 Reinstaller.
    (http://www.apple.com/support/downloads/quicktime652reinstallerforquicktime701.ht ml)
    That should allow your project to run smoothly again. Our machines video cards just don't do well with QT 7.
    NOTE: Some people don't have the problem we had. I believe our problems are made worse by incremental upgrades of QT.
    I hope this helps!

Maybe you are looking for

  • Enhancement for Outbound delivery(VL01n)

    Hi all,          I have a requirement of making delivered quantity = picking quantity.     which is the relevant enhancement for this requirement. thanks in advance sandeep.

  • Where does the rectangle come from?

    I am getting a black outlined transparent frame turning up on my screen and it doesn't go away after rebooting. Does anyone have any idea what it is please?

  • Error executing transaction: org/apache/xpath/XPathAPI

    I have imported one transaction from 12.0.5 MII verstion to 12.1 version and got the following error while running. I think this error is related to some java class. Could you please tell me where to pu the jar for solving this error. In case this er

  • Install hybrid drive on Pavilion DM1 notebook pc

    I bought a Toshiba 1gig hybrid HDD to replace the HDD (500Gig) in my DM1 so I thought it would be a simple job of clone the old to new and swap HDD. How wrong can one be? I've done this before, just a few weeks ago, replacing a HDD on my main PC with

  • How can i upload empty files (0 bytes) in mac, ff 3.6.13?

    im developing an application that has an upload input file. I tested it with ff 4 in ubuntu, and it woks ok, but on mac with ff 3.6.13 I cannot upload 0 Bytes files.