Is Socket.getInputStream() expensive?

Hi,
I am writing an app. that will communicate frequently with other instances of itself on other machines. Now, in the beginning I am going to create socket connections among all apps on all machines. I was thinking of storing the resulting socket variable in a HashMap keyed by machine name. But, then everytime I have to write a message to another machine I would have to do this:
Socket sock = machine2socket.get(machineName);
ObjectOutputStream oos= new ObjectOutputStream(sock.getInputStream());
oos.writeObject(...);I am wondering if it would be more efficient to create the ObjectOutputStream once during initialization and then retrieve that from a HashMap as well.
Any thoughts?

No, it comes free with Java... :-)
First, presumably, the better way would be to create an object to hold the socket, and when you create that object, you pass it the socket to the constructor and in that create your input and output stream wrappers (Object stream, BufferedReaders, whatever), so you aren't creating new ones all the time.
That being said, if you are talking about relatively few clients, I suppose this architecture could be okay. But the more clients running and talking to each other, the more cross connections you have. If you are going to broadcast the same objects to all clients, it might be better to have 1 server that all clients connect to. Then you send objects to the server and let it resend to all other clients. You can have some kinda protocol to send objects to specific clients, get a client list, notification of client connect/disconnect, various other things. This way you have 1 socket connection per client to 1 server, instead of X connections to each of X clients.
Further, the clients have to know where all the other clients are or find them somehow (port scan, for example). A common server is going to be easier to configure then configuring or auto-discovering other clients.

Similar Messages

  • Socket.getOutputStream must precede the socket.getInputStream?!? Why?

    This is server code.......
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class DateServer extends Thread {
       private ServerSocket dateServer;
       public static void main(String argv[]) throws Exception {
         new DateServer();
       public DateServer() throws Exception {
         dateServer = new ServerSocket(3000);
         System.out.println("Server listening on port 3000.");
         this.start();
       public void run() {
         while(true) {
           try {
            System.out.println("Waiting for connections.");
            Socket client = dateServer.accept();
            System.out.println("Accepted a connection from: "+
    client.getInetAddress());
            Connect c = new Connect(client);
           } catch(Exception e) {}
    class Connect extends Thread {
       private Socket client = null;
       private ObjectInputStream ois = null;
       private ObjectOutputStream oos = null;
       public Connect() {}
       public Connect(Socket clientSocket) {
         client = clientSocket;
         try {
          ois = new ObjectInputStream(client.getInputStream());
          oos = new ObjectOutputStream(client.getOutputStream());
         } catch(Exception e1) {
             try {
                client.close();
             }catch(Exception e) {
               System.out.println(e.getMessage());
             return;
         this.start();
       public void run() {
          try {
             oos.writeObject(new Date());
             oos.flush();
             // close streams and connections
             ois.close();
             oos.close();
             client.close();
          } catch(Exception e) {}
    }This is client code....
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class DateClient {
       public static void main(String argv[]) {
          ObjectOutputStream oos = null;
          ObjectInputStream ois = null;
          Socket socket = null;
          Date date = null;
          try {
            // open a socket connection
            socket = new Socket("127.0.0.1", 3000);
            // open I/O streams for objects
            oos = new ObjectOutputStream(socket.getOutputStream());
            ois = new ObjectInputStream(socket.getInputStream());
              System.out.println( "BAU!" );
            // read an object from the server
            date = (Date) ois.readObject();
            System.out.print("The date is: " + date);
            oos.close();
            ois.close();
          } catch(Exception e) {
            System.out.println(e.getMessage());
    }OK.
    Those work just fine. Now if you put socket.getInputStream before the socket.getOutputStream then it hangs!
    Any ideea why this happens and why is not documented... I just lost tow hour tring to figure it out why my program just hangs. After I have set the order as In the example above all works....
    If anyone knows why please share your knowledge...
    Hope this will save others a lot of lost time.

    The order matters because the ObjectOutputStream constructor writes a stream header and the ObjectInputStream constructor reads the header.
    If both ends of the conversation do "new ObjectInputStream()" they both forever wait for the other end to write the header. So one end needs to create the output stream first and the input stream second, and the other end in the other order (or do them in different threads.)
    If it isn't documented it should be IMHO. Re-check the javadocs; if it isn't mentioned file a bug report to Sun. There is a bug parade link on http://java.sun.com/ somewhere.

  • Multiple references to socket.getInputStream()

    I am writing a simple client server game and am trying to pass both input and Objects over the socket stream.
    Is it possible to have:
    BufferedReader ins = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());Or will this cause problems? I am positive of the order of input and objects, so there is no ambiguity on whether to read from ois or ins, but will there be some bad-mojo there anyway?

    Thanks. I've read alot of posts about this and this is the first time I've seen the deprecated readLine solution. Doesn't this seem to be a fairly significant problem? Is BufferedReader supposed to be accepting serialized objects anytime soon?
    I suppose that I could simply close the socket and reestablish a connection using an ObjectInputStream, but what do commercial developers do? Do they just rely on passing String objects or is BufferedReader preferred?

  • Socket.getInputStream() doesn't initialise empty

    I would appreciate any help with the following:
    When using a stream socket to transfer a file from a server to a client, I seem to have trouble with the first byte in the socket input steam.
    I have isolated the code down to the following:
    SERVER CODE
    OutputStream os = sock.getOutputStream();
    int b = 33; // pick an integer to send
    System.out.println("\nFIRST BYTE=" + b); /// here see 33 ok
    os.write(b);
    os.close();
    CLIENT CODE
    InputStream is = sock.getInputStream();
    int b = is.read(); //<<<< here for some reason b = 10????
    System.out.println("\nFIRST BYTE=" + b); /// here display is 10
    I do not get this problem with other inputstreams from System.in (ie. keyboard) or file, only get this problem with the socket inputSteam where first byte is always 10 (I think this is a newline char) , then the following bytes are fine. I am going around in circles trying to figure this one out.
    Note: a work around is to simply read the first byte and discard but this is not explaining the problem.
    Any suggestions?

    Thanks for the replies, I have finally nutted out the problem. For those of you interested . . .
    The fact that that the byte value was 10 (ie linefeed) gave some hints, finally found a stray �\n� was still in inputstream waiting to be read due to an earlier loop error of mine.
    I thought I was instantiating a new inputstream object but in fact was creating and alias for an already created object (containing a left over �\n�).
    Problem solved!
    I have learnt a lot in the 6hrs of pondering this �simple� problem.
    Thanks again

  • Socket.getInputStream hangs

    I have a simple client/server app, and the client hangs when I try to get the input stream coming out of the server. I have the following code on the server:
    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;
    port = 49152;
    server = new ServerSocket(port, 0, InetAddress.getLocalHost());
    sock = server.accept();
    oos = new ObjectOutputStream(sock.getOutputStream());
    ois = new ObjectInputStream(sock.getInputStream());
    String inMsg = (String) ois.readObject();
    oos.writeObject(outMsg);
    oos.close();
    ois.close();
    sock.close();And I try to invoke it with this code on the client:
    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;
    String inMsg = "";
    int port = 49152;
    try {
         Socket sock = new Socket(InetAddress.getLocalHost(), port);
         oos = new ObjectOutputStream(sock.getOutputStream());
         ois = new ObjectInputStream(sock.getInputStream());//the code hangs here
         oos.writeObject(outMsg);
         inMsg = (String) ois.readObject();
            oos.close();
         ois.close();
         sock.close();
    } catch (Exception e) {
         return "";
    return inMsg;
         The code hangs where indicated in the comments. Can someone tell me what I'm doing wrong?
    Edited by: MidnightJava on Apr 10, 2008 4:55 AM

    Can you please explain the rationale for your suggestion? What sort of problem is it addressingThe constructor for ObjectOutputStream writes a header to the stream. The constructor for ObjectInputStream reads it. Try constructing them in the opposite order at both ends and you will see a lovely deadlock. The flush() is required if there is a BufferedOutputStream under the ObjectOutputStream.
    is it a good idea to do it always when creating streams from a socket?It's essential when dealing with object streams. Other streams, no.

  • Reading from socket inputstream returns -1

    I'm using a socket in order to connect to a chat server. The code is:
    Socket socket;
    InputStreamReader isr;
    OutputStreamWriter osw;
    try {
      socket = new Socket(sHost, iPort);
      isr = new InputStreamReader(socket.getInputStream());
      osw = new OutputStreamWriter(socket.getOutputStream());
      int iCharRead;
      char[] buffer = new char[512];
      while((iCharRead=isr.read(buffer, 0, 512))!=-1) {
          // do something
      System.err.println("Error: InputStream has returned -1.");
      System.err.println("\tsocket.isBound()=" + socket.isBound());
      System.err.println("\tsocket.isClosed()=" + socket.isClosed());
      System.err.println("\tsocket.isConnected()=" + socket.isConnected());
      System.err.println("\tsocket.isInputShutdown()=" + socket.isInputShutdown());
      System.err.println("\tsocket.isOutputShutdown()=" + socket.isOutputShutdown());
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {if (isr!=null) isr.close();} catch (Exception ex) {}
      try {if (osw!=null) osw.close();} catch (Exception ex) {}
      try {if (socket!=null) socket.close();} catch (Exception ex) {}
    }Ther server is supposed to be sending data continuously but sometimes, after being connected successfully for a while, the read method returns -1. As you can see in the previous code then I'm checking out some socket information and I get:
    Error: InputStream has returned -1.
         socket.isBound()=true
         socket.isClosed()=false
         socket.isConnected()=true
         socket.isInputShutdown()=false
         socket.isOutputShutdown()=falseThe socket seems to be bounded, it is not closed and isConnected also returns true. Besides, input and output streams are not closed. So, why does the read method return -1? What does it really mean? Is it a problem in the server side, that is overloaded or simply malfunctioning? What can I do in order to keep on reading data from the socket connection? Do I have to close the current socket and reconnect again to the server or is there any other way to recover from this situation?
    Thanks.

    isConnected means was ever connected.
    Check whether isr is closed. If so, the server has disconnected/closed the connection.

  • 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 in java and c++

    I am connecting to a server developed in java that use sys/socket.h, this server use DataInputStream
    class and readUTF so:
    in = new DataInputStream(socket.getInputStream());
    inputString = in.readUTF()
    My application in C++ it use winsock2.h and I utilize the method "send" in order to send the plots to the server
    java got hold of:
    #define MAXLONGITUD 10000
    char     bufEnviados[MAXLONGITUD + 1];
    bufEnviados[0] = (0xff & (longitud >> 8));
    bufEnviados[1] = (0xff & longitud);
    send(sock, bufEnviados,strlen(bufEnviados), 0 );
    I send the two first characters with UTF format so that the server in java could recognize them.
    The application operated correctly it until received an old plot of 6.236 characters later
    from which it close the connection with the socket and it fall my application!
    I have carried out several tests and I don't succeed in sending more than those 6.236 characters, however it achievement receibing whatever quantity of characters without problems!
    Could somebody help me to resolve this problem? I am attempting of everything and I don't achieve it!
    Ahead of time thank you!

    alfaximena wrote:
    #define MAXLONGITUD 10000
    char     bufEnviados[MAXLONGITUD + 1];
    bufEnviados[0] = (0xff & (longitud >> 8));
    bufEnviados[1] = (0xff & longitud);
    send(sock, bufEnviados,strlen(bufEnviados), 0 );
    Are you sending characters or binary data? You mention "plot" which sounds like binary data. You cannot send binary data via character encoding. Characters in java are not just bits, they are mapped values. If you encode it with something like base64 then that should be ok.
    I can only suppose that your testing was with data sets greater than 255, because strlen() would not have worked otherwise.
    Since you have the size then use it rather than using strlen().
    I send the two first characters with UTF format so that the server in java could recognize them.
    The application operated correctly it until received an old plot of 6.236 characters later
    from which it close the connection with the socket and it fall my application!
    There is nothing special about that particular number. So I would guess that the data in that set is the problem. Probably because you are in fact sending binary data. If, for example, a byte with a value of zero showed up in the sequence then strlen() would return an incorrect value compared to the size that you told java you are sending.

  • 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_ ; }
    }

  • A beginner in socket programming

    Ok I am been stuck on this program for the whole day trying to figure out why I cannot connect to my server computer using sockets and threads.
    I am trying to implement a instant messenger program where each user acts has both client/server. Each client creates a listening socket and all use a common port number, (in this case port 4444).
    If client 1 wants to interact with client 2, client 1 query�s my MySQL database for their status. Now if their status is online, retrieve their current ip address. So far so good. My program does not with no problem.
    Now comes the painful part. Now that client 1 knows client 2 is online and has his/hers ip, the next step is to connect to client 2�s listening socket using their ip and the port number 4444. Now after connecting to that socket, a new chat dialog gui is suppose to open from the client 2�s side. This new chat dialog gui (jframe) is a thread so that if other users wishes to interact with client 2, another new chat dialog thread will appear!
    But in my case nope! Has soon as client 1 tries to establish a connection with client 2, boom. Error, connection refused: connect!!
    Now I been searching through Google trying to understand what this means and so far I found null� now I posted before asking what that means and someone told me it means that I forgot to close the sockets and input, output streams. But how can I close it when I cannot even establish a connection with client 2??
    Things I have tried:
    I tried inputting myself, the actual ip of client 2 and guess what� no luck
    I tried the client 2�s computer name, and same thing!
    I tried to create a whole new main class just so that I can open and close the sockets and input/output stream and nope, no luck at all..
    Now that you have a good understanding of my program. Here comes the code:
    I�l start with the user_window, which is the main menu as you call it: this jframe once opened, is suppose to create a server socket to listen for connections. If a connection is made, load the chatdialog gui thread�
    * user_window.java
    * Created on 10 February 2006, 11:50
    package icomm;
    import java.sql.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.net.*;
    import java.io.*;
    * @author jonathan
    public class user_window extends javax.swing.JFrame implements WindowListener {
    protected String crnt_user;
    protected String crnt_ip;
    protected String dummy = "";
    /** Creates new form user_window */
    public user_window() {
    initComponents();
    listeningSocket();
    addWindowListener( this );
    public user_window(String users_name)
    initComponents();
    addWindowListener( this );
    this.crnt_user = users_name;
    private void exit()
    MySQL_queries offline = new MySQL_queries();
    offline.off_status(crnt_user);
    JOptionPane.showMessageDialog(null, "you are about to close the program " + crnt_user, null, JOptionPane.ERROR_MESSAGE);
    MySQL_queries query = new MySQL_queries();
    query.off_status(crnt_user);
    query.reset_ip(crnt_user);
    System.exit(0);
    public void windowClosing(WindowEvent e)
         exit();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    try {
    Buddie_list =(javax.swing.JTree)java.beans.Beans.instantiate(getClass().getClassLoader(), "icomm.user_window_Buddie_list");
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    } catch (java.io.IOException e) {
    e.printStackTrace();
    label = new javax.swing.JLabel();
    demo = new javax.swing.JButton();
    jMenuBar1 = new javax.swing.JMenuBar();
    jMenu1 = new javax.swing.JMenu();
    Close = new javax.swing.JMenuItem();
    jMenu2 = new javax.swing.JMenu();
    profile = new javax.swing.JMenuItem();
    jMenu3 = new javax.swing.JMenu();
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    getContentPane().add(Buddie_list, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, 230, 310));
    getContentPane().add(label, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 390, -1, -1));
    demo.setText("talk to shienna");
    demo.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    demoActionPerformed(evt);
    getContentPane().add(demo, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 360, -1, -1));
    jMenu1.setText("File");
    jMenu1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jMenu1ActionPerformed(evt);
    Close.setLabel("Close");
    Close.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    CloseActionPerformed(evt);
    jMenu1.add(Close);
    jMenuBar1.add(jMenu1);
    jMenu2.setText("Option");
    profile.setText("Edit Profile");
    profile.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    profileActionPerformed(evt);
    jMenu2.add(profile);
    jMenuBar1.add(jMenu2);
    jMenu3.setText("Help");
    jMenuBar1.add(jMenu3);
    setJMenuBar(jMenuBar1);
    pack();
    // </editor-fold>
    private void demoActionPerformed(java.awt.event.ActionEvent evt) {                                    
    // TODO add your handling code here:
    ChatDialog_c chatting = new ChatDialog_c(crnt_user, dummy);
    chatting.setTitle("I-comm");
    chatting.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    chatting.setSize(360, 500);
    chatting.getSize();
    chatting.setLocation(420,200);
    chatting.setVisible(true);
    private void CloseActionPerformed(java.awt.event.ActionEvent evt) {                                     
    // TODO add your handling code here:
    private void demo1ActionPerformed(java.awt.event.ActionEvent evt) {                                     
    // TODO add your handling code here:
    private void show_chat_window()
    ChatDialog chat_gui = new ChatDialog();
    chat_gui.setTitle("chat");
    chat_gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    chat_gui.setSize(366, 480);
    chat_gui.getSize();
    chat_gui.setLocation(420,200);
    chat_gui.setVisible(true);// TODO add your handling code here:
    private void log_offActionPerformed(java.awt.event.ActionEvent evt) {                                       
    private void locate_ip()
    try
    InetAddress a;
    a = InetAddress.getLocalHost(); //get ip addrees
    this.crnt_ip = a.getHostAddress(); //then store it in this variable
    catch(UnknownHostException e)
    JOptionPane.showMessageDialog(null, "Error, cant detect localhost", null, JOptionPane.ERROR_MESSAGE);
    public void windowActivated(WindowEvent e) {}
         public void windowClosed(WindowEvent e) {}
         public void windowDeactivated(WindowEvent e) {}
         public void windowDeiconified(WindowEvent e) {}
         public void windowIconified(WindowEvent e) {}
         public void windowOpened(WindowEvent e)
    locate_ip();
    MySQL_queries new_ip = new MySQL_queries();
    new_ip.update_ip(crnt_user, crnt_ip);
    JOptionPane.showMessageDialog(null,"hello " + crnt_user + " your ip is" + crnt_ip, null, JOptionPane.ERROR_MESSAGE);
    private void listeningSocket()
    ServerSocket serverSocket = null;
    boolean listening = true;
    try
    //listen in port 4444;
    serverSocket = new ServerSocket(4444);
    catch(IOException x)
    JOptionPane.showMessageDialog(null, "cannot listen to port 4444", null, JOptionPane.ERROR_MESSAGE);
    while(listening)
    try
    ChatDialog chat = new ChatDialog(serverSocket.accept());
    catch(IOException x)
    JOptionPane.showMessageDialog(null, "could not open chat window", null, JOptionPane.ERROR_MESSAGE);
    private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {                                      
    // TODO add your handling code here:
    private void profileActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // TODO add your handling code here:
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new user_window().setVisible(true);
    Now for the chatdialog class: I forgot to mention that I have two versions of this class. One that is a thread and the other makes a connection to a thread, hope that makes sence�
    package icomm;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class ChatDialog_c extends javax.swing.JFrame implements WindowListener {
        protected String messege;
        private Socket socket = null;
        protected String ip2;
        private PrintWriter out = null;
        private BufferedReader in = null;
        private String user_name;
        private String status;
        /** Creates new form ChatDialog_c */
        public ChatDialog_c()
            initComponents();
            addWindowListener( this );
         public ChatDialog_c(String ip1)
            initComponents();
            addWindowListener( this );
            this.ip2 = ip1;
            //OptionPane.showMessageDialog(null, "error in closing sockdswdset " + ip2, null, JOptionPane.ERROR_MESSAGE);
         public ChatDialog_c(String user, String status)
            initComponents();
            addWindowListener( this );
            this.user_name = user;
        public void windowClosing(WindowEvent e)
            public void windowActivated(WindowEvent e) {}
         public void windowClosed(WindowEvent e) {
                try
                    in.close();
                    out.close();
                    socket.close();
                catch(IOException x)
                    x.printStackTrace();
                    JOptionPane.showMessageDialog(null, "error in closing socket " + x.getMessage() + ip2, null, JOptionPane.ERROR_MESSAGE);
         public void windowDeactivated(WindowEvent e) {}
         public void windowDeiconified(WindowEvent e) {}
         public void windowIconified(WindowEvent e) {}
          public void windowOpened(WindowEvent e)
              MySQL_queries get_ip = new MySQL_queries();
              this.ip2 = get_ip.find_client(user_name);
               JOptionPane.showMessageDialog(null, user_name + ip2, null, JOptionPane.ERROR_MESSAGE);
                //create socket connection
                try
                    socket = new Socket ("Shienna", 4444);
                    out = new PrintWriter(socket.getOutputStream(), true);
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                catch(UnknownHostException x)
                    x.printStackTrace();
                    JOptionPane.showMessageDialog(null, "unknown  " + x.getMessage() + ip2, null, JOptionPane.ERROR_MESSAGE);
                catch(IOException x)
                    x.printStackTrace();
                    JOptionPane.showMessageDialog(null, "2 " + x.getMessage(), null, JOptionPane.ERROR_MESSAGE);
                 try
                    in.close();
                    out.close();
                    socket.close();
                catch(IOException x)
                    x.printStackTrace();
                    JOptionPane.showMessageDialog(null, "error in closing socket " + x.getMessage() + ip2, null, JOptionPane.ERROR_MESSAGE);
                while(true)
                    try
                        String line = in.readLine();
                        convo_txt.append(line);
                    catch(IOException x)
                        x.printStackTrace();
                        JOptionPane.showMessageDialog(null, "3 " + x.getMessage(), null, JOptionPane.ERROR_MESSAGE);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            convo_txt = new javax.swing.JTextArea();
            jScrollPane2 = new javax.swing.JScrollPane();
            txt_messege = new javax.swing.JTextArea();
            send = new javax.swing.JButton();
            jMenuBar1 = new javax.swing.JMenuBar();
            jMenu1 = new javax.swing.JMenu();
            jMenu2 = new javax.swing.JMenu();
            getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jScrollPane1.setViewportView(convo_txt);
            getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, 220, 280));
            txt_messege.setLineWrap(true);
            jScrollPane2.setViewportView(txt_messege);
            getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 330, 220, 70));
            send.setText("Send");
            send.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    sendActionPerformed(evt);
            getContentPane().add(send, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 420, -1, -1));
            jMenu1.setText("File");
            jMenu1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jMenu1ActionPerformed(evt);
            jMenuBar1.add(jMenu1);
            jMenu2.setText("Option");
            jMenuBar1.add(jMenu2);
            setJMenuBar(jMenuBar1);
            pack();
        // </editor-fold>                       
        private void sendActionPerformed(java.awt.event.ActionEvent evt) {                                    
            String text = txt_messege.getText();
            out.println();
            txt_messege.setText(new String(""));
            convo_txt.append(text);
        private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {                                      
    // TODO add your handling code here:
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ChatDialog_c().setVisible(true);
        }///////////////////////chat dialog thread/////////////////////
    package icomm;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class ChatDialog extends javax.swing.JFrame implements WindowListener, Runnable {
        protected String messege;
        private Socket client_user = null;
        /** Creates new form ChatDialog */
        public ChatDialog()
            initComponents();
            addWindowListener( this );
        public ChatDialog(String txt_messege)
            initComponents();
            addWindowListener( this );
            this.messege = txt_messege;
         public ChatDialog(Socket user)
             initComponents();
             addWindowListener( this );
             this.client_user = user;
        public void run()
            BufferedReader in = null;
            PrintWriter out = null;
            String error = "error has occured ";
            String messege = null;
             try
                //create input and output streams
                in = new BufferedReader(new InputStreamReader (client_user.getInputStream()));
                out = new PrintWriter(client_user.getOutputStream(), true);
                while(true)
                   //read messege sent by user
                   messege = in.readLine();
                   //send data back to user
                   out.println(messege);
                   //append data on the text field
                   convo_txt.append(messege + "\n");
                   //chat_gui.setVisible(true);
                   //-=inputs = new ChatDialog(messege);
               //out.close();
                //in.close();
                //client_user.close();
            catch (IOException e)
                //error messege
                e.printStackTrace();
                JOptionPane.showMessageDialog(null, error + e.getMessage(), null, JOptionPane.ERROR_MESSAGE);
        }If I can sort this problem out I would of completed the main part of my program. I have spent days on this and hope that anyone of you guys can take the time out and help me with my current situation. Thanks

    update:
    i have managed to sort out the connection refused
    i know have anotehr problem: both client2 program freezes as soon as client 1 tries to initiate a connection to client 2!!!!!!!!
    when client 2 logs into teh system. it freezes as soon as i press the button! but when client 1 attempts to conenct to client 2, client 2's program stops freezing and the chatdialog comes up showing nothing and freezes! my chadialog is suppose to show a file menu i made but it doesnt,. both clients freezes at this point. no error messeges occur...

  • Conflict between socket and RMI

    Hi
    I wrote a program in client-server using socket and it was fine. I also wrote a client-server program using RMI. Fine as well. But after I connected the client-server using socket (open socket, send-receive messages, close socket), then use RMI. I got java.rmi.NotBoundException.
    Would anyone have a look and provide your feedback please? Thanks.
    big J
    *****************this is Server.java ***************************
    package single;
    import java.io.*;
    import java.rmi.Naming;
    import java.rmi.RemoteException;
    import java.net.*;
    import java.rmi.*;
    public class Server
    extends Thread {
    public static final int SOCKETPORT = 5555;
    private String serverName;
    public Server() throws IOException {
    System.out.println("*** socket opened ***");
    serverName = new String("localhost");
    ServerSocket serverSocket = new ServerSocket(SOCKETPORT);
    Socket socket = serverSocket.accept();
    InputStream is = socket.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
    System.out.println(bufferedReader.readLine());
    OutputStream os = socket.getOutputStream();
    PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(os), true);
    printWriter.println("from server");
    os.close();
    is.close();
    socket.close();
    System.out.println("*** socket closed ***");
    public void runServer() {
    System.out.println("*** start of run():RMI ***");
    System.setSecurityManager(new SecurityManager());
    try {
    RMIInterfaceImpl rMIInterfaceImpl = new RMIInterfaceImpl();
    Naming.bind("//" + serverName + ":9999/RMIInterface", rMIInterfaceImpl);
    catch (RemoteException ex) {
    catch (MalformedURLException ex) {
    catch (AlreadyBoundException ex) {
    System.out.println("*** end of run():RMI ***");
    public static void main(String args[]) throws Exception {
    Server server = new Server();
    server.runServer();
    ******************this is Client.java **************************
    package single;
    import java.io.*;
    import java.net.*;
    import java.rmi.Naming;
    public class Client {
    private String serverName;
    private final static int SOCKETPORT = 5555;
    public Client() throws IOException {
    serverName = new String("localhost");
    Socket socket = new Socket(serverName, SOCKETPORT);
    OutputStream os = socket.getOutputStream();
    PrintWriter printWriter=new PrintWriter(os, true);
    printWriter.println("from client");
    InputStream is = socket.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
    System.out.println(bufferedReader.readLine());
    is.close();
    os.close();
    socket.close();
    public void runClient() throws Exception {
    System.out.println("*** start of runClient():RMI ***");
    System.setSecurityManager(new SecurityManager());
    RMIInterface rMIInterfaceImpl = (RMIInterface) Naming.lookup(
    "//" + serverName + ":9999/RMIInterface");
    String str = rMIInterfaceImpl.print();
    System.out.println(str);
    rMIInterfaceImpl.serverSide();
    System.out.println("*** end of runClient():RMI ***");
    public static void main(String args[]) throws Exception {
    Client client = new Client();
    client.runClient();
    ***************** this is RMIInterface.java ***********************
    package single;
    import java.rmi.Remote;
    import java.rmi.RemoteException;
    interface RMIInterface
    extends Remote {
    String print() throws RemoteException;
    void serverSide() throws RemoteException;
    ********************* this is RMIInterfaceImpl.java ***************
    package single;
    import java.rmi.RemoteException;
    import java.rmi.server.UnicastRemoteObject;
    public class RMIInterfaceImpl
    extends UnicastRemoteObject
    implements RMIInterface {
    public RMIInterfaceImpl() throws RemoteException {}
    public String print() {
    return new String("hello world");
    public void serverSide(){
    System.out.println("this should appear in serverside");

    I think you have a timing problem between your client and server. As soon as your client and server programs have finished their socket communication, they will both do their "runServer"/"runClient" methods. If the client attempts to lookup the server before the server has registered itself via Naming.bind(), I would expect that's why you're getting a NotBoundException in the client.
    You probably wouldn't use the design of your test client/server for something significant, but a quick and dirty way to make this work might be to have the client call Thread.sleep() for a few seconds before trying to do the lookup.

  • File not found after socket transfer

    I have code written to upload a file to the server. the file uploads fine when i dont specify the dir. It uploads to the server current dir, but when i try to upload it to directory "tmp/uniqueDir/filename" that i create in my code i get filnotfound exception. can someone please help me figure out why?
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.Socket;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    public class ServerUtil {
         String tmpDir;
         String fileName;
         Process proc;
         Runtime runtime = Runtime.getRuntime();
         public static final int BUFFER_SIZE = 1024 * 50;
         private byte[] buffer;
         public ServerUtil() {
              // TODO Auto-generated constructor stub
         public void generateTmpDir(){
              java.util.Date d = new java.util.Date();
              long off = (long) Math.random();
              GregorianCalendar todaysDate=new GregorianCalendar();
              int hour,mins,secs;
              hour=todaysDate.get(Calendar.HOUR);
              mins = todaysDate.get(Calendar.MINUTE);
              secs = todaysDate.get(Calendar.SECOND);
              String SECS = java.lang.Integer.toString(secs);
              String HOUR = java.lang.Integer.toString(hour);
              String MINS = java.lang.Integer.toString(mins);
              String time = HOUR + MINS + SECS;
              /** Unique String Name **/
              String RANDOM_OFFSET = new String ();
              RANDOM_OFFSET =time + d.hashCode() + RANDOM_OFFSET.hashCode()+ off;
              setTmpDir(RANDOM_OFFSET);
              try {
                   proc = runtime.exec("mkdir tmp/" + getTmpDir() );
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         public void uploadFile(Socket socket, BufferedReader rd){
              buffer = new byte[BUFFER_SIZE];
              System.out.println("accepted Socket");
              try {
              BufferedInputStream in =
                   new BufferedInputStream(socket.getInputStream());
              setFileName(rd.readLine());
              System.out.println(fileName);
              BufferedOutputStream out =
                   new BufferedOutputStream(new FileOutputStream("tmp/" + getTmpDir() +"/" + getFileName()));
              int len = 0;
              while ((len = in.read(buffer)) > 0) {
                   out.write(buffer, 0, len);
                   System.out.print("#");
              in.close();
              out.flush();
              out.close();
              socket.close();
              System.out.println("\nDone!");
              catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
          * @return the tmpDir
         public String getTmpDir() {
              return tmpDir;
          * @param tmpDir the tmpDir to set
         public void setTmpDir(String tmpDir) {
              this.tmpDir = tmpDir;
          * @return the fileName
         public String getFileName() {
              return fileName;
          * @param fileName the fileName to set
         public void setFileName(String fileName) {
              this.fileName = fileName;
    }this is the error im getting:
    java.io.FileNotFoundException: tmp/0859124333356700/fileName (A file or directory in the path name does not exist.)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:201)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:153)
    at EpkgArchiveServerUtil.uploadFile(ServerUtil.java:93)
    at ServerThreads.run(ServerThreads.java:38)

    You mean this code?proc = runtime.exec("mkdir tmp/" + getTmpDir() );Does it run with the same working directory as your Java code? And why don't you wait until it finishes? And more to the point, why don't you just use the java.io.File method that will make a directory for you instead of doing a clumsy thing like that?

  • How can i reuse my existing socket connection

    Hi,
    this might sound basic, it probably is:
    As part of my larger project, i have to send and recieve data to multiple socket connections.
    The thing that happens is that everytime i send data, it seems that java is creating a new stream or something (code is multithreaded)
    so as i send 4 items of data, a bit like a chat program sending 4 statements, it creates 4 different streams, instead of using the same stream. therefore when i close the connection, i get:
    java.net.SocketException: Connection reset 4 times.
    i know why.. its because i have added the:
    Socket socket=new Socket(host, port);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
    bit in the same method with the
    out.println(THE DATA....);
    out.flush();
    The thing what i want to do is to create the connection one, and reuse the objects:
    out, in and socket
    to send / recieve the new data.
    please help me guys,
    thanks

    All the threads would be able to get the same reference to....
    class SocketWrapper {
         private final Object readLock = new Object();
         private final Object writeLock = new Object();
         // client side
        public SocketWrapper(String hostname, int port);
         // server side.
        public SocketWrapper(Socket);
         // send data
         public void send(Serializable object) throws IOException;
         // receive data. synchronized(writeLock);
         public Serializable getNext() throws IOException;
         // create a new socket as required, throw IllegalState if server side. synchronized(readLock)
         private void createNewSocket() throws IllegalStateException;
    }The send autoconnects as required. It then send on message/packet/object.
    The getNext autoconnects as required. It reads one message/packet/object and returns.
    This allows multiple threads to access the same socket. It allows data to be sent while a thread is blocking on a read. (Thus two locks)

  • A new socket for every http-request?

    Do I have to make a new socket for every http-request? The code below doesn't work because it is two requests in a row. The first GET works, but the second doesn't. I thought that the purpose of a socket is that you set it up once and then you should be able to do arbitrary communication between the two peers. Maybe that is just the case with sockets only but not if you use sockets to perform http.
    Thank you for your answers! Nice greetings from Austria (not Australia)!
    Stefan :)
    package httptest;
    import javax.net.ssl.*;
    import java.io.*;
    import java.net.*;
    public class Conn2 {
        private PrintWriter out;
        private BufferedReader in;
        private Socket socket;
        public Conn2()
            try {
             socket = new Socket("www.google.at", 80);
             out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));         
             if (out.checkError())
              System.out.println("SSLSocketClient:  java.io.PrintWriter error");
             in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                System.out.println("Connect erfolgreich.");
         } catch (Exception e) {
             System.err.println(e);
        public void test()
            String inputLine;
            // 1. GET
            out.println("GET / HTTP/1.0");
         out.println();
         out.flush();
         try
                while ((inputLine = in.readLine()) != null)
                    System.out.println(inputLine);
            catch(IOException e)
                System.err.println(e);
            // 2. GET
            out.println("GET / HTTP/1.0");
         out.println();
         out.flush();
            try
                while ((inputLine = in.readLine()) != null)
                    System.out.println(inputLine);
            catch(IOException e)
                System.err.println(e);
    }

    Normally in the HTTP protocol, the server will close the connection after every request. So after you do the first GET, the server sends you the result and closes the connection. You have to open a new connection for the second GET.
    You can set specific headers to keep the connection open, which makes things faster if you have to do multiple GET's quickly after another. Lookup the specification of the HTTP protocol on http://www.ietf.org/
    Maybe it's easier to use a HTTP client library like Apache's HTTPClient: http://jakarta.apache.org/commons/httpclient/ so that you don't have to implement all the difficulties of the HTTP protocol yourself.

  • Problem in socket communication please help me!

    server
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    class SocketServer extends JFrame
              implements ActionListener {
         JLabel text1, text2;
         JButton button1, button2;
         JPanel panel;
         JTextField textField1, textField2;
    ServerSocket server = null;
    Socket socket = null;
    BufferedReader in1 = null;
    PrintWriter out1 = null;
    String line1;
    String line2;
    SocketServer(){ //Begin Constructor
              text1 = new JLabel("Send Information:");
              text2 = new JLabel("Receive Information:");
              textField1 = new JTextField(20);
              textField2 = new JTextField(20);
              button1 = new JButton("Send");
              button2 = new JButton("Receive");
              button1.addActionListener(this);
              button2.addActionListener(this);
              panel = new JPanel();
              panel.setLayout(new GridLayout(2,3));
              panel.setBackground(Color.lightGray);
              getContentPane().add(panel);
              panel.add(text1);
              panel.add(textField1);
              panel.add(button1);
              panel.add(text2);
              panel.add(textField2);
              panel.add(button2);
              setSize(500,100);
    } //End Constructor
         public void actionPerformed(ActionEvent event) {
              Object source = event.getSource();
              if(source == button1){
                   //Send data over socket
                   String text = textField1.getText();
                   out1.println(text);
                   textField1.setText(new String(""));
                   //Receive text from server
                   try{
                        String line1 = in1.readLine();
                        System.out.println("Text received :" + line1);
                   } catch (IOException e){
                        System.out.println("Read failed");
                        System.exit(1);
              if(source == button2){
                   textField2.setText(line2);
         public void listenSocket(){
              try{
                   server = new ServerSocket(4444);
              } catch (IOException e) {
                   System.out.println("Could not listen on port 4444");
                   System.exit(-1);
              try{
                   socket = server.accept();
              } catch (IOException e) {
                   System.out.println("Accept failed: 4444");
                   System.exit(-1);
              try{
                   in1 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                   out1 = new PrintWriter(socket.getOutputStream(), true);
              } catch (IOException e) {
                   System.out.println("Accept failed: 4444");
                   System.exit(-1);
              while(true){
                   try{
                        line2 = in1.readLine();
                        //Send data back to client
                        out1.println(line2);
                   } catch (IOException e) {
                        System.out.println("Read failed");
                        System.exit(-1);
         protected void finalize(){
              //Clean up
              try{
                   in1.close();
                   out1.close();
                   server.close();
              } catch (IOException e) {
                   System.out.println("Could not close.");
                   System.exit(-1);
         public static void main(String[] args){
              SocketServer frame = new SocketServer();
              frame.setTitle("Chat (Server)");
              WindowListener l = new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              frame.addWindowListener(l);
              frame.pack();
              frame.setVisible(true);
              frame.listenSocket();
    client
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    class SocketClient extends JFrame
              implements ActionListener {
    JLabel text1, text2;
    JButton button1, button2;
    JPanel panel;
    JTextField textField1, textField2;
    Socket socket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    String line3;
    String line4;
    SocketClient(){ //Begin Constructor
    text1 = new JLabel("Send Information:");
         text2 = new JLabel("Receive Information:");
    textField1 = new JTextField(20);
         textField2 = new JTextField(20);
    button1 = new JButton("Send");
         button2 = new JButton("Receive");
    button1.addActionListener(this);
         button2.addActionListener(this);
    panel = new JPanel();
    panel.setLayout(new GridLayout(2,3));
    panel.setBackground(Color.lightGray);
    getContentPane().add(panel);
    panel.add(text1);
    panel.add(textField1);
    panel.add(button1);
         panel.add(text2);
         panel.add(textField2);
         panel.add(button2);
         setSize(500,100);
    } //End Constructor
         public void actionPerformed(ActionEvent event){
              Object source = event.getSource();
              if(source == button1){
                   //Send data over socket
                   String text = textField1.getText();
                   out.println(text);
                   textField1.setText(new String(""));
                   //Receive text from server
                   try{
                        String line3 = in.readLine();
                        System.out.println("Text received :" + line3);
                   } catch (IOException e){
                        System.out.println("Read failed");
                        System.exit(1);
              if(source == button2){
                   textField2.setText(line4);
         public void listenSocket(){
              //Create socket connection
              try{
                   socket = new Socket("Localhost", 4444);
                   out = new PrintWriter(socket.getOutputStream(), true);
                   in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
              } catch (UnknownHostException e) {
                   System.out.println("Unknown host: Localhost");
                   System.exit(1);
              } catch (IOException e) {
                   System.out.println("No I/O");
                   System.exit(1);
              while(true){
                   try{
                        line4 = in.readLine();
                        //Send data back to client
                        out.println(line4);
                   } catch (IOException e) {
                        System.out.println("Read failed");
                        System.exit(-1);
         public static void main(String[] args){
              SocketClient frame = new SocketClient();
              frame.setTitle("Chat (Client)");
              WindowListener l = new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              frame.addWindowListener(l);
              frame.pack();
              frame.setVisible(true);
              frame.listenSocket();
    There were problems when executing the application
    please help me

    i had no problem running this... make sure you open the server part first and have that sitting and waiting for the client to connect.... then it should work.
    Would you believe that i too am working on the server / socket thing... however my problem is getting the server to read from a database and report back to the client....

Maybe you are looking for

  • How can I transfer music from an old Ipod to a new one?

    I have an older Ipod and just bought an I pod touch.  How can I transfer the music from my old one to the new one? Thanks!

  • Hard Drive Volume Needs to be Repaired - Please help!

    I actually posted this question before, so if you happen to read this for the second time, I do apologize for that. The reason I am posting again is because I couldn't solve the problem, and when I called Apple care today, they asked me to extend my

  • How to run ejb (JServer) client in web browser

    Did anyone try the ClubMed example under $ORACLE_HOME/javavm/demo/examples/ejb/applets/ClubMed? Does anyone know how to run the applets in latest Netscape and/or IE browsers? What do I need to do to set up security, etc. Thanks. null

  • Server Socket only accept from certain IP addresses?

    I'm trying to write a Server Socket that listens for connections. But I only want it to accept connections from known IP addresses. If I'm using the code below: try { serverSocket = new ServerSocket(myPort); } catch (IOException e) { for (;;) { //loo

  • Worklfow Notification Mail

    Hi, The workflow of approval, sends a notification mail, the user who is receiving the mail is French and it has been set in user options on Portal this option, but the mail is being received in English, where is the problem? André Ferreira