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);

Similar Messages

  • 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

  • I did write a simple java program but it is not working please help me.....

    This is the program I wrote LineRect just to draw a line a rectangle etc...... Y it is not working How can i used the same program to run without using applet that is by using awt and swing.........Pls Help me.............
    import java.awt.*;
    import java.io.*;
    public class LineRect
    {public void paint(Graphics g)
         {g.drawLine(10,10, 50,50);
         g.drawRect(10, 60, 40,30);
         g.fillRect(60,10,30,80);
         g.drawRoundRect(10,100,80,50,10,10);
         g.fillRoundRect(20,110,60,30,5,5);
         g.drawLine(100,10,230,140);
         g.drawLine(100,140,230,10);
    <APPLET
    CODE =LineRect.class
    WIDTH=250
    HEIGHT=200>
    </APPLET>

    There are many significant errors here for instance you are using a class file as if it were an applet yet you do not subclass applet. Your code has no init method (if it is to be an applet). Your best bet is to go through the tutorials one step at a time. One thing to consider is to subclass a JPanel and draw on the jpanel overriding the paintComponent method. This can then be added to a JFrame or a JApplet's contentPane and would allow the same graphics in both. But again, please study the tutorials on all of this, otherwise you will be doing hit-or-miss programming, and that is no way to learn.
    Much luck!
    Addendum: Also, if you are just beginning in Java programming, I suggest you start with the basics and not with Swing / AWT / graphics programming. Otherwise you will just end up bruised and disappointed. You have to learn to walk before you can run.
    Edited by: Encephalopathic on Dec 26, 2007 5:09 AM

  • I asked about simple drawing programs but should have specified it needs to have rulers, protractors and circle capabilities.

    I would like a drawing program for quilt design, but it needs to have ruler, protractor ( for angles), and circles. As the particular designs are circles cut into pie wedges, then wedges chopped up and small triangular shapes used to make spiral shape( clockwise, counterclockwise) . I appreciated the info I have already gotten, it was helpful but I need to narrow the list.Thank you.

    What list have you gotten?  I see no post history.

  • 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.

  • 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

  • Need Help with Simple Chat Program

    Hello Guys,
    I'm fairly new to Java and I have a quick question regarding a simple chat program in java. My problem is that I have a simple chat program that runs from its own JFrame etc. Most of you are probably familiar with the code below, i got it from one of my java books. In any case, what I'm attempting to do is integrate this chat pane into a gui that i have created. I attempted to call an instace of the Client class from my gui program so that I can use the textfield and textarea contained in my app, but it will not allow me to do it. Would I need to integrate this code into the code for my Gui class. I have a simple program that contains chat and a game. The code for the Client is listed below.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    public class Client
    extends JPanel {
    public static void main(String[] args) throws IOException {
    String name = args[0];
    String host = args[1];
    int port = Integer.parseInt(args[2]);
    final Socket s = new Socket(host, port);
    final Client c = new Client(name, s);
    JFrame f = new JFrame("Client : " + name);
    f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    c.shutDown();
    System.exit(0);
    f.setSize(300, 300);
    f.setLocation(100, 100);
    f.setContentPane(c);
    f.setVisible(true);
    private String mName;
    private JTextArea mOutputArea;
    private JTextField mInputField;
    private PrintWriter mOut;
    public Client(final String name, Socket s)
    throws IOException {
    mName = name;
    createUI();
    wireNetwork(s);
    wireEvents();
    public void shutDown() {
    mOut.println("");
    mOut.close();
    protected void createUI() {
    setLayout(new BorderLayout());
    mOutputArea = new JTextArea();
    mOutputArea.setLineWrap(true);
    mOutputArea.setEditable(false);
    add(new JScrollPane(mOutputArea), BorderLayout.CENTER);
    mInputField = new JTextField(20);
    JPanel controls = new JPanel();
    controls.add(mInputField);
    add(controls, BorderLayout.SOUTH);
    mInputField.requestFocus();
    protected void wireNetwork(Socket s) throws IOException {
    mOut = new PrintWriter(s.getOutputStream(), true);
    final String eol = System.getProperty("line.separator");
    new Listener(s.getInputStream()) {
    public void processLine(String line) {
    mOutputArea.append(line + eol);
    mOutputArea.setCaretPosition(
    mOutputArea.getDocument().getLength());
    protected void wireEvents() {
    mInputField.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    String line = mInputField.getText();
    if (line.length() == 0) return;
    mOut.println(mName + " : " + line);
    mInputField.setText("");

    Thanks for ur help!i have moved BufferedReader outside the loop. I dont think i am getting exception as i can c the output once.What i am trying to do is repeat the process which i m getting once.What my method does is first one sends the packet to multicasting group (UDP) and other method receives the packets and prints.

  • Numbers 09 not working - I can open the program but only a few files are available, missing blank, checklist and many others. e.g  when I click on a file I get this error: The document "nmbtemplate is invalid. The index.xml file is missing. help.

    Please let me know what I can do to get my Numbers (iWork 09) working properly again.
    Here is what is going on:
    Numbers in iWork 09 not working can't access Blank, Checklist and many other files within Numbers.   I can open the program but only a few files are available. When I click on the file (which also has no icon just the name of the file) this warning appears:
    The document "Blank.nmbtemplate" is invalid.  The index.xml file is missing.
    I recently had to get a new hard drive installed and had the system upgraded and more memory put in by a Mac certified specialist recommended to me from the Apple store in Northbrook because this was the 3rd time my drive went bad but this time it was to old (I got the IMAC- in 2007) and the Apple store could no longer work on it this time so they recommended a few places that had certified Mac specialists.  Since then Numbers is not working right.
    I'm sure it's something simple to fix, but I've tried re installing it and that didn't work.  Appreciate any help.
    Thanks
    AppMare

    There is one way its getting fixed. Once I update my Adobe Illustrator CC to Adobe Illustrator CC 2014 it is further allowing me to go into the system folder and allocate the font to the file so that it can replace it. My only concern now is that our MAC partners who will receive these files back from us have Adobe CS6. We will down save it to CS6 but I hope they won't experience any font issues because of us using CC 2014? Any light you can shed on this?

  • 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)

  • I'm not able to run a simple Hello Program in java

    I have just now installed jdk 1.3.1_2.
    I have set the path and class path.
    I'm able to compile the class without any errors but am not able to run the program.
    when i say java Hello(after compiling Hello.java), i'm seeing the following error:
    Exception in thread "main" java.lang.NoclassDefFoundError:Hello
    Thanks in advance in this regard

    Hmm..
    Okay.. set aside any import or package stuffs.. lets say about a simple HelloWorld program which is called Hello.class. It resides in c:\, which means the full path is c:\Hello.class.
    Make sure you got one of your path as c:\jdk1.3\bin(assuming you are using jdk 1.3).
    If you are in the same directory as Hello.class, which is c:\>, you can execute the class file by typing:
    C:\>java Hello
    If you are not in the same directory and you wishes to run the class file, example you are in directory temp now:
    C:\Temp>java -cp C:\ Hello
    So the cp set will be just c:\. Hope that answers your question somehow.. well... if I never intepret it wrongly.

  • Problem while executing simple java program

    Hi
    while trying to execute a simple java program,i am getting the following exception...
    please help me in this
    java program :import java.util.*;
    import java.util.logging.*;
    public class Jump implements Runnable{
        Hashtable activeQueues = new Hashtable();
        String dbURL, dbuser, dbpasswd, loggerDir;   
        int idleSleep;
        static Logger logger = Logger.getAnonymousLogger();      
        Thread myThread = null;
        JumpQueueManager manager = null;
        private final static String VERSION = "2.92";
          public Jump(String jdbcURL, String user, String pwd, int idleSleep, String logDir) {
            dbURL = jdbcURL;
            dbuser = user;
            dbpasswd = pwd;
            this.idleSleep = idleSleep;
            manager = new JumpQueueManager(dbURL, dbuser, dbpasswd);
            loggerDir = logDir;
            //preparing logger
            prepareLogger();
          private void prepareLogger(){      
            Handler hndl = new pl.com.sony.utils.SimpleLoggerHandler();
            try{
                String logFilePattern = loggerDir + java.io.File.separator + "jumplog%g.log";
                Handler filehndl = new java.util.logging.FileHandler(logFilePattern, JumpConstants.MAX_LOG_SIZE, JumpConstants.MAX_LOG_FILE_NUM);
                filehndl.setEncoding("UTF-8");
                filehndl.setLevel(Level.INFO);
                logger.addHandler(filehndl);
            catch(Exception e){
            logger.setLevel(Level.ALL);
            logger.setUseParentHandlers(false);
            logger.addHandler(hndl);
            logger.setLevel(Level.FINE);
            logger.info("LOGGING FACILITY IS READY !");
          private void processTask(QueueTask task){
            JumpProcessor proc = JumpProcessorGenerator.getProcessor(task);       
            if(proc==null){
                logger.severe("Unknown task type: " + task.getType());           
                return;
            proc.setJumpThread(myThread);
            proc.setLogger(logger);       
            proc.setJumpRef(this);
            task.setProcStart(new java.util.Date());
            setExecution(task, true);       
            new Thread(proc).start();       
         private void processQueue(){       
            //Endles loop for processing tasks from queue       
            QueueTask task = null;
            while(true){
                    try{
                        //null argument means: take first free, no matters which queue
                        do{
                            task = manager.getTask(activeQueues);
                            if(task!=null)
                                processTask(task);               
                        while(task!=null);
                    catch(Exception e){
                        logger.severe(e.getMessage());
                logger.fine("-------->Sleeping for " + idleSleep + " minutes...hzzzzzz (Active queues:"+ activeQueues.size()+")");
                try{
                    if(!myThread.interrupted())
                        myThread.sleep(60*1000*idleSleep);
                catch(InterruptedException e){
                    logger.fine("-------->Wakeing up !!!");
            }//while       
        public void setMyThread(Thread t){
            myThread = t;
        /** This method is only used to start Jump as a separate thread this is
         *usefull to allow jump to access its own thread to sleep wait and synchronize
         *If you just start ProcessQueue from main method it is not possible to
         *use methods like Thread.sleep becouse object is not owner of current thread.
        public void run() {
            processQueue();
        /** This is just another facade to hide database access from another classes*/
        public void updateOraTaskStatus(QueueTask task, boolean success){
            try{         
                manager.updateOraTaskStatus(task, success);
            catch(Exception e){
                logger.severe("Cannot update status of task table for task:" + task.getID() +  "\nReason: " + e.getMessage());       
        /** This is facade to JumpQueueManager method with same name to hide
         *existance of database and SQLExceptions from processor classes
         *Processor class calls this method to execute stored proc and it doesn't
         *take care about any SQL related issues including exceptions
        public void executeStoredProc(String proc) throws Exception{
            try{
                manager.executeStoredProc(proc);
            catch(Exception e){
                //logger.severe("Cannot execute stored procedure:"+ proc + "\nReason: " + e.getMessage());       
                throw e;
         *This method is only to hide QueueManager object from access from JumpProcessors
         *It handles exceptions and datbase connecting/disconnecting and is called from
         *JumpProceesor thread.
        public  void updateTaskStatus(int taskID, int status){       
            try{
                manager.updateTaskStatus(taskID, status);
            catch(Exception e){
                logger.severe("Cannot update status of task: " + taskID + " to " + status + "\nReason: " + e.getMessage());
        public java.sql.Connection getDBConnection(){
            try{
                return manager.getNewConnection();
            catch(Exception e){
                logger.severe("Cannot acquire new database connection: " + e.getMessage());
                return null;
        protected synchronized void setExecution(QueueTask task, boolean active){
            if(active){
                activeQueues.put(new Integer(task.getQueueNum()), JumpConstants.TH_STAT_BUSY);
            else{
                activeQueues.remove(new Integer(task.getQueueNum()));
        public static void main(String[] args){
                 try{
             System.out.println("The length-->"+args.length);
            System.out.println("It's " + new java.util.Date() + " now, have a good time.");
            if(args.length<5){
                System.out.println("More parameters needed:");
                System.out.println("1 - JDBC strign, 2 - DB User, 3 - DB Password, 4 - sleeping time (minutes), 5 - log file dir");
                return;
            Jump jump = new Jump(args[0], args[1], args[2], Integer.parseInt(args[3]), args[4]);
            Thread t1= new Thread(jump);
            jump.setMyThread(t1);      
            t1.start();}
                 catch(Exception e){
                      e.printStackTrace();
    } The exception i am getting is
    java.lang.NoClassDefFoundError: jdbc:oracle:thin:@localhost:1521:xe
    Exception in thread "main" ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
    JDWP exit error AGENT_ERROR_NO_JNI_ENV(183):  [../../../src/share/back/util.c:820] Please help me.....
    Thanks in advance.....sathya

    I am not willing to wade through the code, but this portion makes me conjecture your using an Oracle connect string instead of a class name.
    java.lang.NoClassDefFoundError: jdbc:oracle:thin:@localhost:1521:xe

  • TCP/IP socket programming in ABAP

    Hi,
    Is there any method of TCP socket programming in ABAP? For example is there any function module for creating a socket for a IP address and port number. After that, is it possible to send binary/text data to a connected IP/port destination. I need such a solution because I need to send raw data (native commans) to barcode printer on our network which has a static IP address and listens incoming data through a fixed port number specified in its documentation. For a solution, I coded some .NET VB and built a small application that acts as a RFC server program which can be called by SAP according to definitions I made in SM59 (I defined a new TCP connection and it works well sometimes!). In this application, data coming from SAP are transferred to the barcode printer. This is achived by the .NET Socket class library. This solution works well but after a few subsequent call from SAP, connection hangs! SAP cannot call the application anymore, I test the connection in SM59 and it also hangs, so I need to restart the VB application, but this is unacceptable in our project.
    As a result, I decided to code the program that will send data to the printer in ABAP as a function module or subroutine pool, so is there any way to create a socket in ABAP and connect to specific IP/port destination? I searched for possible function modules in SE37 and possible classes in SE24 but unfortunately I could not find one. For example, do know any kind of system function in ABAP (native commands executed by CALL statement), that can be used for this purpose?
    I would appreciate any help,
    Kind regards,
    Tolga
    Edited by: Tolga Togan Duz on Dec 17, 2007 11:49 PM

    Hi,
    I doubt that there is a low level API for sockets in ABAP. There is API for HTTP but probably that won't help you. As a workaround you can use external OS commands (transactions SM69 and SM49). For example on Unix you can use netcat to transfer file. Your FM needs to dump data into folder and then call netcat to transfer file.
    Cheers

  • Need help on with simple email program

    i have been set a task to create a simple email program that has the variables of the sender the recipient the subject the content and a date object representing when the email was sent (this is just to be set to the current system date)
    It also needs to include a constructor with four String arguments, i.e the sender, receiver, subject and content. The constructor has to initialise the date of the email then transfer the values of the input parameters to the relevant attributes. If any values of the strings aren'nt given, the string �Unknown� should be set as the value.
    I was given a java file to test the one i am to create, but some of the values are not given, if anyone could be of anyhelp or just point me in the right direction then i would be very greatfull, ive posted the code for the test file i have been given below, thanks.
    public class SimpleEmailTest {
         public static void main( String[] args ) {
              SimpleEmail email;     // email object to test.
              String whoFrom;          // sender
              String whoTo;          // recipient
              String subject;          // subject matter
              String content;          // text content of email
              static final String notKnown = "Unknown";
              email = new SimpleEmail
    (notKnown, notKnown, notKnown, notKnown);
              System.out.println( "SimpleEmail: " +
    "\n    From: " + email.getSender() +
    "\n      To: " + email.getRecipient() +
    "\n Subject: " + email.getSubject() +
    "\n    Date: " + 
    email.getDate().toString() +
    "\n Message: \n" + email.getContent() + "\n";
              email.setSender( "Jimmy Testsender");
              email.setRecipient( "Sheena Receiver");
              email.setSubject( "How are you today?");
              email.setContent( "I just wrote an email class!");
              System.out.println( "SimpleEmail: " +
    "\n    From: " + email.getSender() +
    "\n      To: " + email.getRecipient() +
    "\n Subject: " + email.getSubject() +
    "\n    Date: " + 
    email.getDate().toString() +
    "\n Message: \n" + email.getContent() + "\n";
         }

    Start by writing a class named SimpleEmail, implement a constructor with four arguments in it, and the methods that the test code calls, such as the get...() and set...() methods. The class probably needs four member variables too.
    public class SimpleEmail {
        // ... add member variables here
        // constructor
        public SimpleEmail(String whoFrom, String whoTo, String subject, String content) {
            // ... add code to the constructor here
        // ... add get...() and set...() methods here
    }

Maybe you are looking for