KXML or Socket+Serializable

Hi,
I don't Know if to use kxml or socket+serializable's object for the comunication between client and server.
which is the better choice?
(I do not speak English very well)
Thanks

Hey;
Right again cweed. You are getting rich, he he he : )
I used a BufferInputStream.read(byteBuffer, 0, 250);
Then I used a loop on each of the bytes to convert the byte buffer to a string. Does that sound about right?
Thanks, Dan

Similar Messages

  • Socket serialization(Reply asap)

    How to serialize a socket object without using RMI.
    Otherwise please tell me how to retrieve a socket object which has been converted to string using socket.toString().

    OK.
    let's say that you got the string from your RMI method:
    String host=rmi_object.getHost();
    the create a new socket:
    java.net.Socket s=new java.net.Socket(host, port);
    of course, the rmi method can return an serialized object witch contains all the information you want, host, port, etc.
    public class MyObject implements Serializable
    private String host;
    private int port;
    public void setHost(String newHost){
    host=newHost;
    public String getHost(){
    return host;
    //and so on .....
    Hope this helps.

  • URGENT : Pass non-serializable objects over sockets

    I am working with a non-serializable class.I can't change it to serializable(since it's an API class).I can't create a subclass either as I need to pass the same exact Object .I have tried wrapping it in a serializable class (as transient )but then the particular object that I need is not serialized.Is there a way to pass non-serializable objects over sockets?.Some other way of doing this?. Should i use RMI or Externalize?. Any help would be appreciated.

    {snip}
    Like this:
    public class SerializableLibraryClass extends
    LibraryClass implements Serializable {
    }Then you've got a class that is exactly the same as
    LibraryClass, but is now serializable.Not quite. The base class still isn't Serializable. Take, for example, the following code:
    public class A
        public int a1;
    public class B extends A implements Serializable
        public int b1;
    B beforeSend = new B();
    beforeSend.a1 = 1;
    beforeSend.b1 = 2;
    objectOutputStream.writeObject(b);
    B afterSend = (B)(objectInputStream.readObject());Both beforeSend and afterSend have fields a1 and b1. For beforeSend, a1 = 1 and b1 = 2. For afterSend, b1 = 2 but a1 = 0. The superclass wasn't Serializable; therefore, its members weren't Serialized and, when the object was created on the other side of the stream, a1 was left at its initial value.
    In short, you can't just Serialize the subclass. That Serialization won't apply to its superclasses.

  • Pass non-serializable objects over sockets

    I am working with a non-serializable class.I can't change it to serializable(since it's an API class).I can't create a subclass either as I need to pass the same exact Object .I have tried wrapping it in a serializable class (as transient )but then the particular object that I need is not serialized.Is there a way to pass non-serializable objects over sockets?.Some other way of doing this?.

    Have you considered leaving it in situ and using RMI to manipulate it remotely ?
    To be a little pedantic, if you need the "same exact object" then there's no technique that will work for you, since you can only copy an object between JVMs, not move it.
    D.

  • Socket Object Serialization StreamCorruptionException

    Hi,
    I'm currently attempting to send objects across the network via serialization. I can send Strings back and forth from client to server and server to client without a problem, but when i try to send and recieve a different object (one i wrote) i get EOFException or StreamCorruptionException. This was working before i added a considerable amout to the code. I just don't understand why it breaks now. Any help would be greatly appreciated. And i apologize in advance for leaving all of my print statements in.
    public class ServerThread extends Thread {
         private Socket socket = null;
         private Buyer buyer = null;
         private Bid bid = null;
         private Auctioneer auctioneer = null;
         private int clientId;
         private String userInfo[] = new String[2];
         private static final String REQUEST_NAME = "1";
         private static final String SUCCESS = "SUCCESS";
         private static final String FAIL = "FAIL";
        private static ObjectOutputStream out = null;
        private static ObjectInputStream in = null;
         public ServerThread(Socket socket, Auctioneer auctioneer, int clientId) throws SocketException{
              super("ServerListenerThread");
              this.socket = socket;
              this.auctioneer = auctioneer;
              this.clientId = clientId;
              this.setPriority( 10 );
         public boolean userExists(String name){
              for (Iterator it = auctioneer.getBuyers().iterator(); it.hasNext();){
                   buyer = (Buyer)it.next();
                   if(buyer.getName().equals( userInfo[0])) return true;
              return false;
         public void run(){
              try {
                   in = new ObjectInputStream(socket.getInputStream());
                   out = new ObjectOutputStream(socket.getOutputStream());
                   Integer cid = new Integer(clientId);
                   bid = null;
                   buyer = null;
                   String msg = null;
                   try{
                        // listen for login: user/password
                        msg = (String)in.readObject();
                        userInfo[0] = msg.substring(0,msg.indexOf(","));
                        userInfo[1] = msg.substring(msg.indexOf(",") + 1, msg.length());
                        if(userExists(userInfo[0])){
                             System.out.println("wes already logged in");
                             out.writeObject(FAIL);
                             return;
                        else
                             System.out.println("wes not logged in");
                             out.writeObject(SUCCESS);
                        out.writeObject(cid);
                        out.flush();
                        buyer = (Buyer)in.readObject();
                        auctioneer.addBuyer( buyer);
                   int n = 0;
                   while ((bid = (Bid)in.readObject()) != null && !auctioneer.exit){
                        auctioneer.addBid(bid);
                        n++;
                        System.out.println("this was bid: " + bid.getBidAmt() + " this many times " + n);
                   }catch(SocketException e){
                        System.out.println("Client " + clientId + " Disconnected!!!");
                        //controller.notifyLostClient(buyer);
                        auctioneer.removeBuyer( buyer);
                        auctioneer.update();
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (ClassNotFoundException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();}
    Client Side
    public boolean connect(){
              boolean connect = false;
              System.out.println("trying to connect...");
                   for(int i = 0; i <=9; i++){
                        System.out.println("trying to connect...");
                        try {
                             socket = new Socket(ip, PORT);
                             socket.setTcpNoDelay( true );
                             System.out.println("this doesn't take long");
                             out = new ObjectOutputStream(socket.getOutputStream());
                             in = new ObjectInputStream(socket.getInputStream());
                             connect = true;
                             break;
                        }catch(UnknownHostException e){
                             System.out.println("No Server At: " + ip[i].getHostAddress() );
                        }catch(IOException e){
                             System.out.println("No Server At: " + ip[i].getHostAddress() );
                   if(connect){
                        return true;
                   else{
                        int i = JOptionPane.showConfirmDialog(null,
                                  " Couldn't find " + HOST + "\n Try Again?"
                                  , "WARNING", JOptionPane.YES_NO_OPTION,
                                  JOptionPane.QUESTION_MESSAGE);
                        if (i == 1)
                             System.exit(1);
                        else {
                             return false;
                   return false;
         public boolean login(){
              try {
                   try {
                        String msg = USER + "," + PASSWORD;
                        out.writeObject( msg );
                        out.flush();
                        msg = (String)in.readObject();
                        System.out.println(msg);
                        if(msg.equals("SUCCESS")){
                             clientId = (Integer)in.readObject();
                             System.out.println("Client " + clientId.toString() );
                             msg = "TEST";
                             out.writeObject( msg );
                             out.flush();
                             Bid newBid = new Bid(buyer, 12);
                             out.writeObject(newBid);
                             out.flush();
                             buyer = new Buyer(USER,clientId,socket.getLocalAddress().getHostName());
                             out.writeObject(buyer);
                             out.flush();
                             Object obj = in.readObject();
                        else{
                             int i = JOptionPane.showConfirmDialog(null,
                                       " System could not log you in\n Try Again?"
                                       , "WARNING", JOptionPane.YES_NO_OPTION,
                                       JOptionPane.QUESTION_MESSAGE);
                             if (i == 1)
                                  System.exit(1);
                             else
                                  return false;
                   } catch (ClassNotFoundException e1) {
                        e1.printStackTrace();
              } catch (IOException e2) {
                   e2.printStackTrace();
              new ClientListenerThread(controller).start();
              return true;
    Any Ideas???

    I fogot to give the code of the objects im sending across
    package taxsale.shared;
    import java.io.Serializable;
    * Created on May 27, 2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author Admin
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    public class Bid implements Serializable{
         private int bidAmt;
         private Buyer buyer;
         private String time;
         public Bid(){
              this.buyer = new Buyer("", new Integer(0), "");
              this.bidAmt = 19;
         public Bid(Buyer buyer, int bidAmt){
              this.buyer = buyer;
              this.bidAmt = bidAmt;
          * @return Returns the bidAmt.
         public int getBidAmt() {
              return bidAmt;
          * @return Returns the buyer.
         public Buyer getBuyer() {
              return buyer;
         public void setTime(String time){
              this.time = time;
         public String getTime(){
              return time;
    package taxsale.shared;
    import java.io.Serializable;
    * Created on May 26, 2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author Admin
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    public class Buyer implements Serializable{
         private String name;
         private Integer id;
         private Boolean connected;
         private String cName;
         public Buyer(){
         public Buyer(String name, Integer id, String cName){
              this.name = name;
              this.id = id;
              this.cName = cName;
              this.connected = new Boolean(false);
          * @return Returns the id.
         public Integer getId() {
              return id;
          * @param clientId
         public void setId(Integer clientId) {
              id = clientId;
          * @return Returns the cName.
         public String getCName() {
              return cName;
          * @param name The cName to set.
         public void setCName(String name) {
              cName = name;
          * @return Returns the user.
         public String getName() {
              return name;
          * @param user The user to set.
         public void setName(String name) {
              this.name = name;
    }Thanks

  • Serialization over sockets

    Hi All!
    So i've decided to perform serialization over sockets - so i made a server that has an ObjectOutputStream and a client that has ObjectInputStream and i wrote a Properties object.
    I managed to get passed the EOFException problem and the same object writing problem (using reset()), but i've read that this isn't efficient, and on top it all it has the problem of blocking.
    I've read some posts regarding Serialization and NIO but i couldn't get from them what i should do - so can someone plz explain to me:
    1) How can i write objects to sockets using NIO
    2) Furthermore - if this really solves the memory and efficiency problems
    3) A code sample or a ref. would really be appriciated.
    Regards,
    Snayit

    Basically I would ask myself if I really need NIO - for MOST purposes the old-blocking IO is very good and much easier to use.
    One of the biggest problems with blocking IO is, that for thousands of clients you need an own thread which causes many OSes to truggle.
    I really recommend buffering the streams! (Via BufferedInput/OutputStream) but do not forget to flush() them if you really want the data to be sent.
    If you want to use NIO you have to write the object-data into a byte-array (creating a bytearrayoutputstream -> ObjectOutputStream) and writing this byte-arrays.
    hope this helps, lg Clemens

  • How can i Serialize the Image Object to Write it in Socket

    Hi Friends
    I'm trying Write the Object of Image class of Awt Package to Socket.
    What i want to do is ?
    I am trying to Capture the Client Screen using Robot Class of awt and then want to write the Same object of Image to Socket.. and then Display it on other Client..
    Also when i use the Robot Class in Applets it Give me an Exception Class not Found java.awt.Robot.

    that's because Robot is a 1.3 class and the client is running a jvm earlier than that. you can use the java plugin to have that class available. But I don't know if that would even work though because of the security manager may not let you do that. You will need to have the client set certain security permissions or you can sign your applet to get permission and have the client accept it.
    David

  • OptionalDataException when using serialize and socket timeout

    hi,
    i'm using ObjectInputStream and ObjectOutputStream to send objects through a socket.
    I sometimes get the following exception: OptionalDataException, with the exception message as null.
    does anyone know why or how can i handle it?
    i'm sure that all i'm sending is objects.

    yes i did.
    they talk about not sending object,
    or increasing the timeout to around 3 seconds.
    i'm writing a program that its consept is writing diffrent objects, and 3 sec of blocking time is a lot for me.
    i saw that there is a lot of confusion about this problem, and thought that we might put it to an end (plus i'll solve the problem in my program :-) ).
    alon

  • Data written to socket getting lost?  or perhaps out of order?

    I'm trying to fix a bug in Flashmog. The bug is described in more detail here.
    Basically what is happening is that my Flash client claims that it is calling functions that don't arrive at the server -- or they arrive, but the socket data is out of order and therefore is garbled.  I've stared at the source code for hours and tried a lot of trial-and-error type stuff and added trace statements to see if I can find the problem and I'm not having any luck.
    In particular, there's class I have called RPCSocket that extends the AS3 Socket class so I can serialize data structures before sending them across a socket.  At one point, this RPCSocket class calls super.writeBytes and super.Flush.  It is the point at which I send all data out of my client. The data is binary data in AMF3 format.
              public function executeRPC(serviceName:String, methodName:String, methodParams:Array):void {
                   if (!this.connected) {
                        log.write('RPCSocket.executeRPC failed. ' + methodName + ' attempted on service ' + serviceName + ' while not connected', Log.HIGH);
                        throw new Error('RPCSocket.executeRPC failed. ' + methodName + ' attempted on service ' + serviceName + ' while not connected.');
                        return;
                   var rpc:Array = new Array();
                   rpc[0] = serviceName;
                   rpc[1] = methodName;
                   rpc[2] = methodParams;
                   var serializedRPC:ByteArray = serialize(rpc);
                   if (!serializedRPC) {
                        log.write('RPCSocket.executeRPC failed.  Serialization failed for method ' + methodName + ' on service ' + serviceName, Log.HIGH);
                        dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR, false, false, 'RPCSocket.executeRPC failed.  Serialization failed for method ' + methodName + ' on service ' + serviceName));
                   super.writeUnsignedInt(serializedRPC.length);
                   super.writeBytes(serializedRPC);
                   super.flush();
              } // executeRPC
    Can someone recommend a way for me to store without corruption, conversion, or filtering or translation of any kind *all* of the information sent across this socket? I'd like to write it to a file.  I'm guessing that keep a global ByteArray var and storing the info there might work, but I'm wondering how I might get the contents of that ByteArray into a file so I can inspect it.
    Also, I'm wondering if I might be able to inspect what flash actually sends out on the socket?  I have a sneaking suspicion that data I supply to super.writeBytes may be sent out of order or may not actually get sent across the socket.  This bug I'm talking about only seems to happen under high-stress situations when I'm sending dozens of messages per second across this one socket.

    oops...forgot link to bug description: http://flashmog.net/community/viewtopic.php?f=5&t=549

  • Problem with Serialization from Threads

    I'm quite new to java threads, and i'm doing a simple server.
    It opens a thread for every socket connection that is opened, so the Socket is extern to the Thread.
    When I try to serialize on the socket a Vector (that contains Vectors, etc..) that is extern to the Thread, the first time everything goes ok, but when the thread modifies some variables in some objects contained in a vector(that, i repeat is extern to the thread), the serialized object doesn't seem to change, and the client continues receiving the same variables, without change.
    In a first time i thought that maybe creating a thread, the second one took a copy of the space of addresses of the main one(and so when i modify a variable from a thread the variable in the main thread didn't change), but i read that java uses the same space of addresses for every thread, so i don't really know what it could be.
    Maybe i've not been clear so i make an example:
    MyType is a class containing some fields, let's put x and y
    In the class MainClass i have an istance of this class, and also a socket and from here i open a thread of class MyThread
    MyThread modifies x and y in a object of MyType contained in the "3D array" that is in MainClass
    Then from that thread i serialized on the socket (which was been passed by MainClass).
    Well, doing this way the vector that the client receives has always the x and y fields unchanged.
    Please help me, cause i've been thinking all day of what it could be and found nothing on the web.
    Also sorry for my poor english.

    I thought that could be the problem, but it wasn't.
    The client still receives the vector with objects
    unchanged.
    I think the problem is that the thread can only access
    to a copy of the class that contains the vector, and
    so when i send the real one, it isn't changed.not likely. one of the things about threads is that they share everything but local (read: non-Object) data. All objects are accessible to any thread of your application, as long as that thread has a reference to it.

  • Problem with socket object writing

    hi,
    I made this little programm , with a class point , a server and a client.
    I try to send via the socket several point object.
    If send differents objects ( with several new point(... )) it works fine , but if i send the same object changing only the properties it doesn't work. Changing are not applicate.
    Here is the code.
    // POINT
    import java.io.Serializable;
    import java.awt.*;
    public class point implements Serializable{
        private int x_;
        private int y_;
        private Color c_;
        public point(int x, int y, Color c) {
           x_=x;
           y_=y;
           c_=c;
        public int get_x() { return x_ ; }
        public int get_y() { return y_ ; }
        public void set_x(int x) { x_=x ; }
        public void set_y(int y) { y_=y ; }
        public Color get_color() { return c_ ; }
    // SERVER
    import java.io.*;
    import java.net.*;
    public class s {
        public s()
            try
                ServerSocket server = new java.net.ServerSocket(80);
                java.net.Socket client  = server.accept();
                ObjectInputStream Istream_ = new ObjectInputStream(client.getInputStream());
                ObjectOutputStream Ostream_ = new ObjectOutputStream(client.getOutputStream());
                for(int i=0;i<4;i++)
                    point p_read = (point)Istream_.readObject();
                    System.out.print("x="+p_read.get_x());
                    System.out.println(" y="+p_read.get_y());
             catch (Exception exception) { exception.printStackTrace(); }
        public static void main(String args[])
         s s_ = new s();
    // CLIENT
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    public class c {
        public c()
            try
                ipJDialog ipjd = new ipJDialog();
                String ip = ipjd.getvalue();
                Socket socket  = new Socket(ip,80);
                System.out.println("connection avec serveur reussi");
                ObjectOutputStream Ostream_ = new ObjectOutputStream(socket.getOutputStream());
                ObjectInputStream Istream_ = new ObjectInputStream(socket.getInputStream());
                point p1 = new point(50,50, new Color(255,0,0));
                Ostream_.writeObject(p1);
                point p2 = new point(22,30, new Color(255,0,0));
                Ostream_.writeObject(p2);
                point p3 = new point(8,7, new Color(255,0,0));
                Ostream_.writeObject(p3);
                point p4 = new point(2,1, new Color(255,0,0));
                Ostream_.writeObject(p4);
             catch (Exception exception) {exception.printStackTrace();}
        public static void main(String args[])
         c c_ = new c();
    // DIALOG TO GET IP FROM INPUTBOX
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class ipJDialog extends JDialog implements ActionListener {
        private String ip_;
        private JTextArea jta_;
        private JTextField jtf_;
        private JButton jb1_;
        public ipJDialog()
            this.getContentPane().setLayout(null);
            this.setTitle("Entrez l'IP du serveur");
            this.setSize(220,100);
            this.setModal(true);
            ip_= "localhost";
            jta_ = new JTextArea("IP du serveur :");
            jta_.setBounds(10,5, 90,20);
            jta_.setOpaque(false);
            jta_.setEditable(false);
            getContentPane().add(jta_);
            jtf_ = new JTextField();
            jtf_.setBounds(110,5, 90,20);
            jtf_.requestFocus();
            getContentPane().add(jtf_);
            jb1_ = new JButton("OK");
            jb1_.setBounds(10,30, 90,30);
            jb1_.addActionListener(this);
            getContentPane().add(jb1_);
            this.setVisible(true);
        public String getvalue() { return ip_ ; }
        public void actionPerformed(ActionEvent evt)
            String ChoixOption = evt.getActionCommand();
         if(ChoixOption.equals("OK"))
                ip_=jtf_.getText();
                this.setVisible(false);
    if I replace in client :
             point p1 = new point(50,50, new Color(255,0,0));
                Ostream_.writeObject(p1);
                point p2 = new point(22,30, new Color(255,0,0));
                Ostream_.writeObject(p2);
                point p3 = new point(8,7, new Color(255,0,0));
                Ostream_.writeObject(p3);
                point p4 = new point(2,1, new Color(255,0,0));
                Ostream_.writeObject(p4);
    by :
             point p = new point(50,50, new Color(255,0,0));
                Ostream_.writeObject(p);
                p.set_x(20);
                p.set_x(22);
                Ostream_.writeObject(p);
                p.set_x(55);
                p.set_x(32);
                Ostream_.writeObject(p);
                p.set_x(14);
                p.set_x(88);
                Ostream_.writeObject(p);
    I doesn't work , i receive a point with 50,50 ( the first one ) four times ...If you can explain me me why and what can I do ...
    Thx.

    For ObjectOutputStream, multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written. State of a object will be recorded so that the ObjectOutputStream doesn't writes the same object to the outputstream when the object was refered by multiple references. So, when you tried to write the same object agains into the ObjectOutputStream, the ObjectOutputStream doesn't write the object, but passed the as a reference to the outputstream... In this case, on the other side, the ObjectInputStream will receive this reference and it will return the reference of this object (which is previous created when this object was passed over on the 1st time). This caused the ObjectInputStream will return a "unchanged" object even your object have changed before you write it agains to the ObjectOutputStream.
    My explaination maybe not that good... hope you can understand... :)

  • Problem with socket and object writing

    Hi,
    I programm this client/server app, the client has a point (graphic ) , the server has a point and when the mouse is moving it moves the point and the new position is send via the socket.
    The probleme is that i don't receive the good thing.
    When i display the coord of the point before sending it's good , but when receiving from the socket the coords are always the same ...
    i don't understand .
    Well , try and tell me ...
    Thx.

    oups, the program can be usefull ...
    import java.applet.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class server_JFrame extends javax.swing.JFrame implements MouseListener,MouseMotionListener{
    point p1,p2;
    server s;
    public server_JFrame()
    this.setSize(600,400);
    addMouseListener(this);
    addMouseMotionListener(this);
    p2=new point(50,50,new Color(0,0,255));
    p1=new point(200,200,new Color(255,0,0));
    s = new server(p2,this);
    public void paint(Graphics g)
    super.paint(g);
    g.setColor(p1.get_color());
    g.fillOval(p1.get_x(), p1.get_y(),10,10);
    g.setColor(p2.get_color());
    g.fillOval(p2.get_x(), p2.get_y(),10,10);
    public void mouseClicked(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseDragged(MouseEvent e) {}
    public void mouseMoved(MouseEvent e)
    p1.set_x(e.getX());
    p1.set_y(e.getY());
    s.write_point(p1);
    repaint();
    public static void main(String args[])
         server_JFrame sjf = new server_JFrame();
    sjf.setDefaultCloseOperation(EXIT_ON_CLOSE);
         sjf.setTitle("server");
    sjf.show();
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    public class server {
    point p_;
    Container c_;
    ObjectInputStream Istream_;
    ObjectOutputStream Ostream_;
    public server(point p,Container c)
    p_=p;
    c_=c;
    try
    ServerSocket server = new java.net.ServerSocket(80);
    System.out.println("attente d'un client");
    java.net.Socket client = server.accept();
    System.out.println("client accept�");
    Istream_ = new ObjectInputStream(client.getInputStream());
    Ostream_ = new ObjectOutputStream(client.getOutputStream());
    ThreadRead tr = new ThreadRead(Istream_,p_,c_);
    catch (Exception exception) { exception.printStackTrace(); }
    public void write_point(point p)
    try
    System.out.print("x="+p.get_x());
    System.out.println(" y="+p.get_y());
    Ostream_.flush();
    Ostream_.writeObject(p);
    Ostream_.flush();
    catch (Exception exception) {exception.printStackTrace();}
    import java.applet.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class client_JFrame extends javax.swing.JFrame implements MouseListener,MouseMotionListener{
    point p1,p2;
    client c;
    public client_JFrame()
    this.setSize(600,400);
    addMouseListener(this);
    addMouseMotionListener(this);
    p1=new point(50,50,new Color(0,0,255));
    p2=new point(200,200,new Color(255,0,0));
    c = new client(p2,this);
    public void paint(Graphics g)
    super.paint(g);
    g.setColor(p1.get_color());
    g.fillOval(p1.get_x(), p1.get_y(),10,10);
    g.setColor(p2.get_color());
    g.fillOval(p2.get_x(), p2.get_y(),10,10);
    public void mouseClicked(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseDragged(MouseEvent e) {}
    public void mouseMoved(MouseEvent e)
    p1.set_x(e.getX());
    p1.set_y(e.getY());
    c.write_point(p1);
    repaint();
    public static void main(String args[])
         client_JFrame cjf = new client_JFrame();
    cjf.setDefaultCloseOperation(EXIT_ON_CLOSE);
         cjf.setTitle("client");
    cjf.show();
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    public class client {
    point p_;
    Container c_;
    ObjectInputStream Istream_;
    ObjectOutputStream Ostream_;
    public client(point p,Container c)
    p_=p;
    c_=c;
    try
    ipJDialog ipjd = new ipJDialog();
    String ip = ipjd.getvalue();
    Socket socket = new Socket(ip,80);
    System.out.println("connection avec serveur reussi");
    Ostream_ = new ObjectOutputStream(socket.getOutputStream());
    Istream_ = new ObjectInputStream(socket.getInputStream());
    ThreadRead tr = new ThreadRead(Istream_,p_,c_);
    catch (Exception exception) {*exception.printStackTrace();*/System.out.println("connection avec serveur echou�");}
    public void write_point(point p)
    try
    System.out.print("x="+p.get_x());
    System.out.println(" y="+p.get_y());
    Ostream_.flush();
    Ostream_.writeObject(p);
    Ostream_.flush();
    catch (Exception exception) {exception.printStackTrace();}
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    public class client {
    point p_;
    Container c_;
    ObjectInputStream Istream_;
    ObjectOutputStream Ostream_;
    public client(point p,Container c)
    p_=p;
    c_=c;
    try
    ipJDialog ipjd = new ipJDialog();
    String ip = ipjd.getvalue();
    Socket socket = new Socket(ip,80);
    System.out.println("connection avec serveur reussi");
    Ostream_ = new ObjectOutputStream(socket.getOutputStream());
    Istream_ = new ObjectInputStream(socket.getInputStream());
    ThreadRead tr = new ThreadRead(Istream_,p_,c_);
    catch (Exception exception) {*exception.printStackTrace();*/System.out.println("connection avec serveur echou�");}
    public void write_point(point p)
    try
    System.out.print("x="+p.get_x());
    System.out.println(" y="+p.get_y());
    Ostream_.flush();
    Ostream_.writeObject(p);
    Ostream_.flush();
    catch (Exception exception) {exception.printStackTrace();}
    import java.io.Serializable;
    import java.awt.*;
    public class point implements Serializable{
    private int x_;
    private int y_;
    private Color c_;
    public point(int x, int y, Color c) {
    x_=x;
    y_=y;
    c_=c;
    public int get_x() { return x_ ; }
    public int get_y() { return y_ ; }
    public void set_x(int x) { x_=x ; }
    public void set_y(int y) { y_=y ; }
    public Color get_color() { return c_ ; }
    }

  • Small input program (html) using sockets.

    I'm having problems with the following whenever a cd is inputted via cdinput.html it runs cdprocess.jsp to create an XML document with DOM in memory this is sent to the server and is later printed out to the users screen. The server must be started in order for it to work. For some reason it doesn't seem to be working? In cd process i'm suppose to modify a few things they've been numbered i've complete all of them so far but i'm not sure if #4 is correct. I've been stuck on it for a while now, any help would be appreciated.
    cdinput.html
    <html>
    <head><title></title></head>
    <body>
    <br /><center>
    <table width="500" border="0"
      cellpadding="4" cellspacing="0">
    <tr>
      <td bgcolor="lightblue">
      <font color="white" face="Arial"><b>CD Input</b>
      </font></td>
    </tr>
    <tr>
      <td>
      <form method="post" action="cdprocess.jsp">
        <table>
         <tr>
          <td><b>CD Title:</b></td>
          <td><input type="text" name="cdtitle" size="20"></td>
         </tr>
         <tr>
          <td><b>CD Artist:</b></td>
          <td><input type="text" name="cdartist" size="20"></td>
         </tr>
         <tr>
          <td><b>Track 1 title:</b></td>
          <td><input type="text" name="track1title" size="20"></td>
         </tr>
         <tr>
          <td><b>Track 1 time:</b></td>
          <td><input type="text" name="track1time" size="20"></td>
         </tr>
         <tr>
          <td><b>Track 1 rating:</b></td>
          <td><select name="track1rating">
           <option value="1"> 1 </option>
           <option value="2"> 2 </option>
           <option value="3"> 3 </option>
           <option value="4"> 4 </option>
           <option value="5"> 5 </option>
           </select></td>
         </tr>
        </table><br />
      <input type="submit" value="Enter CD">
      </form> 
      </td>
    </tr>
    </table>
    </center>
    </body>
    </html>
    SimpleServer2.java
    import java.net.*;
    import java.io.*;
      The server half of a simple client/server application.
      The server that reads lines of text from a socket and sends
      back a copy of the same text to the client.
      The main difference between this example and SimpleServer is that
      this one allows multiple sequential (not concurrent) connections
      from clients.
    public class SimpleServer2 {
        public static final int serverListenPort = 10151;
          The main method is the entry point for the application.
          Because this is a simple application for testing, everything
          is done inside the main method.
          @param args Arguments entered on the command-line.
        public static void main(String[] args) throws IOException {
            ServerSocket myServerSocket = null;
            // Try to open a server socket listening on specified listen port
            try {
                myServerSocket = new ServerSocket(serverListenPort);
            catch (IOException e) {
                System.err.println("Could not listen on port" + serverListenPort);
                System.err.println("Perhaps somebody else is using that port number??");
                System.exit(1);
               * This is where the difference begins.
               * Note the while(true) loop, which means that we will
               * accept an infinite number of connections from clients,
               * one at a time.  The server will never exit by itself,
               * you will have to kill it manually by typing Ctrl-C
               * at the command line where it is running.
              while(true) {
                 // Create a variable to hold the socket that we get when a
                 // new client connects
                 Socket myClientSocket = null;
                 // Accept a new connection from a client
                 // This method call will block until a client does connect
                 try {
                     myClientSocket = myServerSocket.accept();
                 catch (IOException e) {
                     System.err.println("Accept failed.");
                     System.exit(1);
                 // Now that we have a socket, the reading and writing code
                 // is basically the same as in the client application.
                 // We start by getting hold of the output stream to write data
                 // to the socket, and the input stream to read data from the socket.
                 PrintWriter out = new PrintWriter(myClientSocket.getOutputStream(), true);
                 BufferedReader in = new BufferedReader(
              new InputStreamReader(myClientSocket.getInputStream()));
                 String inputLine, outputLine;
                 // Now use a loop to read in lines of text from the client, and
                 // echo them back to the client
                 // Note that this time we do NOT break out of the loop.
                   // We will just wait for the client to close the connection,
                   // and when it does, our inputLine will be null and then we
                   // will break out of the loop.
                 while ((inputLine = in.readLine()) != null) {
                      outputLine = inputLine;
                      out.println(outputLine);
                   // If we have broken out of the loop, we can assume that
                   // the input is closed.  The output probably is too, but
                   // just in case, we'll close it anyway.
                 out.close();
    cdprocess.jsp
    <%@page import="java.io.*"%>
    <%@page import="java.net.*"%>
    <%@page import="javax.xml.parsers.*"%>
    <%@page import="org.w3c.dom.*"%>
    <%@page import="org.apache.xml.serialize.*"%>
    <%!
       public static final String serverHost = "cdserver";
       public static final int serverPort = 10151;
    %>
    <hr />
    <pre>
    <%
            Socket mySocket = null;          // socket object
            PrintWriter sockOut = null;      // to send data to the socket
            BufferedReader sockIn = null;    // to receive data from the socket
            try {
                   //  #1 add line that creates a client socket
                   mySocket = new Socket(serverHost, serverPort);
                   // #2 add lines that create input and output streams
                   //               attached to the socket you just created
                    sockOut = new PrintWriter(mySocket.getOutputStream(), true);
                    sockIn = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
            } catch (UnknownHostException e) {
                throw e; // This time the JSP can handle the exception, not us
            } catch (IOException e) {
                throw e; // This time the JSP can handle the exception, not us
    String cdTitle, cdArtist, track1Title, track1Time, track1Rating;
    // Retrieve the HTML form field values
    cdTitle = request.getParameter("cdtitle");
    cdArtist = request.getParameter("cdartist");
    track1Title = request.getParameter("track1title");
    track1Time = request.getParameter("track1time");
    track1Rating = request.getParameter("track1rating");
    * Our goal is to build an XML document in memory using DOM.
    * We will build it up one tree-node at a time, and when it is
    * finished, we will write the whole lot out to a file on disk.
    /* Start of the DOM code */
    // Create a new DOM factory, and from that a new DOM builder object
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    // Note that we are creating a new (empty) document
    Document document = builder.newDocument();
    // The root element of our document wil be <cd>
    // It gets stored as the child node of the whole document (it is the root)
    Element rootElement = document.createElement("cd");
    document.appendChild(rootElement);
    // Create an element for the CD title called <title>
    Element cdTitleElement = document.createElement("title");
    // Add a text code under the <title> element with the value that
    // the user entered into the title field of the web form (cdTitle)
    cdTitleElement.appendChild(document.createTextNode(cdTitle));
    // Place the <title> element underneath the <cd> element in the tree
    rootElement.appendChild(cdTitleElement);
    // Create an <artist> element with the form data, place underneath <cd>
    Element cdArtistElement = document.createElement("artist");
    cdArtistElement.appendChild(document.createTextNode(cdArtist));
    rootElement.appendChild(cdArtistElement);
    // Create a <tracklist> element and place it underneath <cd> in the tree
    // Note that it has no text node associated with it (it not a leaf node)
    Element trackListElement = document.createElement("tracklist");
    rootElement.appendChild(trackListElement);
    // In this example we only have one track, so it is not necessary to
    // use a loop (in fact it is quite silly)
    // But the code below is included to demonstrate how you could loop
    // through and add a set of different tracks one by one if you
    // needed to (although you would need to have the track data already
    // stored in an array or a java.util.Vector or similar
    int numTracks = 1;
    for (int i=0; i<numTracks; i++) {
      String trackNum = Integer.toString(i+1);
      // Note that this element has an attribute associated with it that
      // is the track number.  It will look like:  <track id="1">
      // The <track> element is placed underneath <tracklist> in the tree
      Element trackElement = document.createElement("track");
      trackElement.setAttribute("id", trackNum);
      trackListElement.appendChild(trackElement);
      // Track title element called <title>, placed underneath <track>
      Element trackTitleElement = document.createElement("title");
      trackTitleElement.appendChild(document.createTextNode(track1Title));
      trackElement.appendChild(trackTitleElement);
      // Track time element called <time>, placed underneath <track>
      Element trackTimeElement = document.createElement("time");
      trackTimeElement.appendChild(document.createTextNode(track1Time));
      trackElement.appendChild(trackTimeElement);
      // Track rating element called <rating>, placed underneath <track>
      Element trackRatingElement = document.createElement("rating");
      trackRatingElement.appendChild(document.createTextNode(track1Rating));
      trackElement.appendChild(trackRatingElement);
    /* End of DOM code */
    /* Start of serialization code */
    // Create a new OutputFormat - this is something specific needed by the
    // XMLSerializer class shown below.  We will specify that we want the
    // generated XML to be formatted with indenting so it is easy to read.
    OutputFormat format = new OutputFormat();
    format.setIndenting(true);
    * Note: the next line of code is the one change to serialization
    // Create a new XMLSerializer that will be used to write out the XML
    // This time we will serialize it to the socket
    // #3 change this line so that it serializes to the socket,
    // not to the "out" object
    XMLSerializer serializer = new XMLSerializer(writer, format);
    // Call the serialize() method, and pass to it out XML document
    // stored in memory in a DOM tree
    serializer.serialize(document);
    /* End of serialization code */
            // Print out a message to indicate the end of the data, and
            // flush the stream so all the data gets sent now
            sockOut.println("<!--QUIT-->");
            sockOut.flush();
              BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
              String fromServer;
              String fromUser;
               #4 add a while loop that reads text from the
              server socket input stream, line by line, and prints
              it out to the web page, using out.println(...);
              Note that because the reply from the server will contain
              XML, you will need to call upon the toHTMLString() method
              defined below to escape the < and > symbols so that they
              will display correctly in the web browser.
              Also note that as you receive the reply back from the
              server, you should look out for the special <!--QUIT-->
              string that will indicate when there is no more data
              to receive.
            while ((fromServer = sockIn.readLine()) != null) {
              out.println(sockIn.readLine());
                // If the reply from the server said "QUIT", exit from the
                // while loop by using a break statement.
                if (fromServer.equals("QUIT")) {
                    out.println("Connection closed - good bye ...");
                // Print the text from the server out to the user's screen
                out.println("Reply from Server: " + fromServer);
                // Now read a line of text from the keyboard (typed by user)
                fromUser = stdIn.readLine();
                // If it wasn't null, print it out to the screen, and also
                // print a copy of it out to the socket
                if (fromUser != null) {
                    out.println("Client: " + fromUser);
                    sockOut.println(fromUser);
            // Close all the streams we have open, and then close the socket
            sockOut.close();
            sockIn.close();
            mySocket.close();
    %>
    <%!
        This method will escape any special HTML characters in a string
        of text.  For example, if you are trying to print out an XML
        document using a JSP, you need to escape all the '<' and '>' tags
        so that the web browser will not try and treat them as HTML.
        Note that generic utility code like this would usually be put into
        a JavaBean, but is put in the JSP here for simplicity.
        This code taken from H. Bergsten, JavaServer Pages, O'Reilly, 2001.
    private static String toHTMLString(String in) {
            StringBuffer out = new StringBuffer();
            for (int i = 0; in != null && i < in.length(); i++) {
                char c = in.charAt(i);
                if (c == '\'') {
                    out.append("'");
                else if (c == '\"') {
                    out.append(""");
                else if (c == '<') {
                    out.append("<");
                else if (c == '>') {
                    out.append(">");
                else if (c == '&') {
                    out.append("&");
                else {
                    out.append(c);
            return out.toString();
    %>
    </pre>
    <hr />

    the following also has me stumped:
    // #3 change this line so that it serializes to the socket,
    // not to the "out" object
    i tried changing the first parameter to the socket "mySocket" but it just gives me a compilation error.

  • Reading text from server socket stream

    I have a basic cd input program i've been trying to figure out the following problem for a while now, the user enters the artist and title etc and then a DOM (XML) file is created in memory this is then sent to the server. The server then echos back the results which is later printed on a html page by reading the replys from the server line by line.
    The server must be run it listens for clients connecting the clients connect and send DOM documents through the following jsp code.
    <%@page import="java.io.*"%>
    <%@page import="java.net.*"%>
    <%@page import="javax.xml.parsers.*"%>
    <%@page import="org.w3c.dom.*"%>
    <%@page import="org.apache.xml.serialize.*"%>
    <%!
       public static final String serverHost = "cdserver";
       public static final int serverPort = 10151;
    %>
    <hr />
    <pre>
    <%
            Socket mySocket = null;          // socket object
            PrintWriter sockOut = null;      // to send data to the socket
            BufferedReader sockIn = null;    // to receive data from the socket
            try {
                //  #1 add line that creates a client socket
                mySocket = new Socket(serverHost, serverPort);
                // #2 add lines that create input and output streams
                //            attached to the socket you just created
                 sockOut = new PrintWriter(mySocket.getOutputStream(), true);
                 sockIn = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
            } catch (UnknownHostException e) {
                throw e; // This time the JSP can handle the exception, not us
            } catch (IOException e) {
                throw e; // This time the JSP can handle the exception, not us
    String cdTitle, cdArtist, track1Title, track1Time, track1Rating;
    // Retrieve the HTML form field values
    cdTitle = request.getParameter("cdtitle");
    cdArtist = request.getParameter("cdartist");
    track1Title = request.getParameter("track1title");
    track1Time = request.getParameter("track1time");
    track1Rating = request.getParameter("track1rating");
    // Create a new DOM factory, and from that a new DOM builder object
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    // Note that we are creating a new (empty) document
    Document document = builder.newDocument();
    // The root element of our document wil be <cd>
    // It gets stored as the child node of the whole document (it is the root)
    Element rootElement = document.createElement("cd");
    document.appendChild(rootElement);
    // Create an element for the CD title called <title>
    Element cdTitleElement = document.createElement("title");
    // Add a text code under the <title> element with the value that
    // the user entered into the title field of the web form (cdTitle)
    cdTitleElement.appendChild(document.createTextNode(cdTitle));
    // Place the <title> element underneath the <cd> element in the tree
    rootElement.appendChild(cdTitleElement);
    // Create an <artist> element with the form data, place underneath <cd>
    Element cdArtistElement = document.createElement("artist");
    cdArtistElement.appendChild(document.createTextNode(cdArtist));
    rootElement.appendChild(cdArtistElement);
    // Create a <tracklist> element and place it underneath <cd> in the tree
    // Note that it has no text node associated with it (it not a leaf node)
    Element trackListElement = document.createElement("tracklist");
    rootElement.appendChild(trackListElement);
    // In this example we only have one track, so it is not necessary to
    // use a loop (in fact it is quite silly)
    // But the code below is included to demonstrate how you could loop
    // through and add a set of different tracks one by one if you
    // needed to (although you would need to have the track data already
    // stored in an array or a java.util.Vector or similar
    int numTracks = 1;
    for (int i=0; i<numTracks; i++) {
      String trackNum = Integer.toString(i+1);
      Element trackElement = document.createElement("track");
      trackElement.setAttribute("id", trackNum);
      trackListElement.appendChild(trackElement);
      // Track title element called <title>, placed underneath <track>
      Element trackTitleElement = document.createElement("title");
      trackTitleElement.appendChild(document.createTextNode(track1Title));
      trackElement.appendChild(trackTitleElement);
      // Track time element called <time>, placed underneath <track>
      Element trackTimeElement = document.createElement("time");
      trackTimeElement.appendChild(document.createTextNode(track1Time));
      trackElement.appendChild(trackTimeElement);
      // Track rating element called <rating>, placed underneath <track>
      Element trackRatingElement = document.createElement("rating");
      trackRatingElement.appendChild(document.createTextNode(track1Rating));
      trackElement.appendChild(trackRatingElement);
    OutputFormat format = new OutputFormat();
    format.setIndenting(true);
    // Create a new XMLSerializer that will be used to write out the XML
    // This time we will serialize it to the socket
    // #3 change this line so that it serializes to the socket,
    // not to the "out" object
    XMLSerializer serializer = new XMLSerializer(writer, format);
    serializer.serialize(document);
            // Print out a message to indicate the end of the data, and
            // flush the stream so all the data gets sent now
            sockOut.println("<!--QUIT-->");
            sockOut.flush();
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
            String fromServer;
            String fromUser;
             #4 add a while loop that reads text from the
            server socket input stream, line by line, and prints
            it out to the web page, using out.println(...);
            Note that because the reply from the server will contain
            XML, you will need to call upon the toHTMLString() method
            defined below to escape the < and > symbols so that they
            will display correctly in the web browser.
            Also note that as you receive the reply back from the
            server, you should look out for the special <!--QUIT-->
            string that will indicate when there is no more data
            to receive.
            while ((fromServer = sockIn.readLine()) != null) {
            out.println(sockIn.readLine());
                // If the reply from the server said "QUIT", exit from the
                // while loop by using a break statement.
                if (fromServer.equals("QUIT")) {
                    out.println("Connection closed - good bye ...");
                // Print the text from the server out to the user's screen
                out.println("Reply from Server: " + fromServer);
                // Now read a line of text from the keyboard (typed by user)
                fromUser = stdIn.readLine();
                // If it wasn't null, print it out to the screen, and also
                // print a copy of it out to the socket
                if (fromUser != null) {
                    out.println("Client: " + fromUser);
                    sockOut.println(fromUser);
            // Close all the streams we have open, and then close the socket
            sockOut.close();
            sockIn.close();
            mySocket.close();
    %>
    I'm suppose to modify the commented sections labled with #.
    #1,2 are correct but i have doubts on the 3rd and 4th modification.
    for #3 i changed so i serializes to the socket not to the "out" object:
    from
    XMLSerializer serializer = new XMLSerializer(out, format);
    to
    XMLSerializer serializer = new XMLSerializer(writer, format);
    with "out" it prints out some of the results entered but it just hangs i'm thinking it might be the while loop that i added in #4. If i changed it to serialize the socket XMLSerializer serializer = new XMLSerializer(writer, format); it doesn't print out nothing at all; just a blank screen where it hangs.
    I can post the rest of the code (server thats in java and cdinput.html) but since i want to keep my post short and if required i'll post it later on i also omitted some of the code where it creates the DOM textnodes etc to keep my post short.

    On your previous thread, why did you say the server was using http POST and application/xml content type when it quite obviously isn't, but a direct socket communication that abuses XML comments for message end delimiters?
    The comments imply you need to wait for "<!--QUIT-->" on a line by itself, but your loop is waiting for "QUIT".
    Pete

  • How to use channel with sockets?

    Hello
    i am impleme3nted a sinple client/server application. The serv handles multiple connection via multithread(one thread per connection). Here is my code
    private void listen(int port) throws IOException {
    ss = new ServerSocket(port); // Create the ServerSocket
    System.out.println("Listening on " + ss);
    while (true) {
    Socket s = ss.accept(); // Grab the next incoming connection
    //s.setKeepAlive(true);
    System.out.println("Connection from " + s);
    // Create a DataOutputStream for writing data to the other side
    //dout = new ObjectOutputStream(s.getOutputStream());
    // dout.useProtocolVersion(ObjectOutputStream.PROTOCOL_VERSION_1);
    Thread clientThread =new ServerThread(s); // Create a new thread for this
    clientThread.start();
    // connection
    My client and server exchange object(serializable). How can i change this in order to add the ServerSocketChannel feature so that one thread deals with many connection?
    thanks a lot
    sebastien

    Hi, yes i have seen that document
    but i don't really know how i cna use it to update my code with channel feature.
    how can we do, please provide me an update of my previously posted code. I would be so thankful.
    thanks a lot
    sebastien

Maybe you are looking for