Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / December 2004

Tip: Looking for answers? Try searching our database.

Problem with sockets

Thread view: 
yo_mismo - 07 Dec 2004 15:57 GMT
Hello,

i'm programing a client/server aplication that does the following
1. The client pass a file name to the server.
2. The server reads that file and sends to the client the info.

I execute the server and it waits for petitions. Then, i execute the client
and everything goes fine. The server does his work and waits another client.
The problem comes when i execute another client. The problem is this:
java.net.ConnectException: Connection refused
       at java.net.PlainSocketImpl.socketConnect(Native Method)
       at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:305)
       at
java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:171)
       at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:158)
       at java.net.Socket.connect(Socket.java:452)
       at java.net.Socket.connect(Socket.java:402)
       at java.net.Socket.<init>(Socket.java:309)
       at java.net.Socket.<init>(Socket.java:124)
       at Servidor.enviar(Servidor.java:79)
       at Servidor.leer(Servidor.java:34)
       at Servidor.main(Servidor.java:105)

i've revise the code several times but i don't find the problem. If someone
have an idea of what is happening and knows how to fix it it would be a big
Xmas present for me :)

Thanxs

SERVER======================================================================
=========================
import java.io.*;
import java.net.*;

public class Server
{
   public static void read(byte [] data) throws IOException
   {
       DataInputStream din = new DataInputStream(new
ByteArrayInputStream(data));
               .........
               .........
               .........
               .........
               .........
                       data = towrite(tam, file_data);
                       send(data);
               }
               catch(IOException e)
               {
                       System.out.println("ERROR: IOException");
                       e.printStackTrace();
               }
      }

   public static byte [] towrite(int tam, byte [] file_read) throws
IOException
   {
       Message msj = new Message(tam, file_read);

       return msj.getBytesDR();
   }

   public static byte [] receive(ServerSocket listener) throws IOException
   {
       Socket aClient        = listener.accept();
       InputStream      in   = aClient.getInputStream();
       DataInputStream  din  = new DataInputStream(in);

       byte [] b = new byte[200];
       din.read(b);
       aClient.close();

       return b;
   }

   public static ServerSocket listener() throws IOException
   {
       ServerSocket listener = new ServerSocket(4645);
       return listener;
   }

    public static void send(byte [] data) throws IOException
    {
         Socket server server         = new Socket(SERVER_NAME,4647);
        OutputStream out  = server.getOutputStream();
        DataOutputStream dout = new DataOutputStream(out);

       dout.write(data);
       dout.close();
       out.close();
       server.close();
    }

   public static void main(String[] args)
   {
       boolean listening = true;

       try
       {
               ServerSocket listener = (ServerSocket)null;
               listener = listener();

               while (listening)
               {
                       byte [] data = receive(listener);
                       read(data);
               }
               listener.close();
       }
       catch(IOException e)
       {
               System.out.println("ERROR: IOException");
               e.printStackTrace();
               System.exit(-1);
       }
   }
}
END
SERVER======================================================================
=====================
CLIENT======================================================================
=========================
import java.io.*;
import java.net.*;

public class Client
{

   public static byte [] towrite(String fichero) throws IOException
   {
       Message msj = new Message(fichero, 0, 10);

       return msj.getBytesRD();
   }

   public static void send(byte [] data) throws IOException
   {
       try
       {
               Socket server         = new Socket(SERVER_NAME,4645);
               OutputStream     out  = server.getOutputStream();
               DataOutputStream dout = new DataOutputStream(out);

               dout.write(data);
               dout.close();
               data = rereive();
               read(data);
               out.close();
               server.close();
       }
       catch(UnknownHostException uhe)
       {
               uhe.printStackTrace();
       }

   }

   public static void read(byte [] data) throws IOException
   {
        DataInputStream din = new DataInputStream(new
ByteArrayInputStream(data));

              .........
               .........
               .........
               .........
               .........
   }

   public static byte [] receive() throws IOException
   {
       ServerSocket listener = new ServerSocket(4647);
       Socket aClient        = listener.accept();
       InputStream      in   = aClient.getInputStream();
       DataInputStream  din  = new DataInputStream(in);

       byte [] b = new byte[200];
       din.read(b);
       listener.close();

       return b;
   }

   public static void main(String[] args)
   {
       try
       {
           String file_name= "file";
           byte [] data = towrite(nom_fich);
           send(data);
       }
       catch(IOException e)
       {
           System.out.println("ERROR: IOException");
           e.printStackTrace();
       }
   }
}
END
CLIENT======================================================================
=========================
Gordon Beaton - 07 Dec 2004 16:05 GMT
> I execute the server and it waits for petitions. Then, i execute the
> client and everything goes fine. The server does his work and waits
> another client. The problem comes when i execute another client. The
> problem is this: java.net.ConnectException: Connection refused

Don't close the listen socket after the client exits. Close only the
client socket returned by accept().

/gordon

Signature

[  do not email me copies of your followups  ]
g o r d o n + n e w s @  b a l d e r 1 3 . s e

yo_mismo - 07 Dec 2004 17:21 GMT
First of all thanx for your interest :)

I've closed the socket aClient in the function Client.receive and not the
listener but goes wrong yet.
When i execute the client the second time it remains in stand by as the
server. If i close(^C) the client and execute it again(only the client), it
conects with the server but the server returns nothing.
I think it's a socket that lost the comunication after the first client is
executed and this is why i can't use it again.
But i don't know how to fix it ;(

> > I execute the server and it waits for petitions. Then, i execute the
> > client and everything goes fine. The server does his work and waits
[quoted text clipped - 9 lines]
> [  do not email me copies of your followups  ]
> g o r d o n + n e w s @  b a l d e r 1 3 . s e
Gordon Beaton - 07 Dec 2004 19:25 GMT
> I've closed the socket aClient in the function Client.receive and
> not the listener but goes wrong yet. When i execute the client the
[quoted text clipped - 3 lines]
> lost the comunication after the first client is executed and this is
> why i can't use it again. But i don't know how to fix it ;(

Your code and your explanation are unclear.

Regardless, here are some tips:

- in the server, separate the part where you accept incoming
 connections to the ServerSocket, from the part where you handle a
 single connection (the Socket returned by accept()).

- in your your earlier example, it appears from send() that the server
 connects to the client in order to send data. If the client has
 connected to the server, the server can send the data using the same
 socket connection. There is no need to make a second connection for
 data in the reverse direction.

- if you handle each client in a separate thread, the server can
 accept new connections without waiting for earlier ones to finish.

- when you read from an InputStream, there is no guarantee that you
 will read all of the requested data at once. This is especially true
 when the stream comes from a Socket. You may need to read several
 times. Check the return value from read(). Or, use the readFully()
 method of DataInputStream.

- have a look at the Java tutorial. There is a simple example of a TCP
 client and server in the networking trail:

 http://java.sun.com/docs/books/tutorial/networking/index.html

/gordon

Signature

[  do not email me copies of your followups  ]
g o r d o n + n e w s @  b a l d e r 1 3 . s e



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.