Jump to content

How to create socket application?

- - - - -

  • Please log in to reply
4 replies to this topic

#1
thatsme

thatsme

    Programmer

  • Members
  • PipPipPipPip
  • 176 posts
Hi. I am trying to create socket application, but i always get exception:
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.peek(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.peek(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at BookStoreServer$ConnectionHandler.run(BookStoreServer.java:72)

Here are my classes BookStoreServer and Client:
public class Client{
    public static void main(String args[]){
        try{
            final int PORT = 10000;
            Socket newClientSocket = new Socket("78.60.65.181", PORT);
            ObjectOutputStream out = new ObjectOutputStream(newClientSocket.getOutputStream());
            ObjectInputStream in = new ObjectInputStream(newClientSocket.getInputStream());
            String fromServer, fromUser;
            
            String[] authors = {"a", "b"};
            Book book1 = new Book("1", authors, "2000");
            Package userPackage = new Package("bookRegistration");
            Object[] objectsToSend = {};
            objectsToSend[0] = book1;
            userPackage.setObjects(objectsToSend);
            out.writeObject(userPackage);
            out.flush();
            
            out.close();
            in.close();
            newClientSocket.close();
        } catch (UnknownHostException e) {
            System.out.println("Host was not found");
            System.out.println("2");
            System.exit(1);
        } catch (IOException e) {
            System.out.println("Failed to get I/O");
            System.out.println("3");
            e.printStackTrace();
            System.exit(1);
        }
    }
}

public class BookStoreServer{
    
    static final int PORT = 10000; 
    static final int MAX_QUEUE_LENGTH = 5;
    
    static BooksList booksList = new BooksList();
    
    public static void main(String args[]) throws UnknownHostException{    
        
        ServerSocket serverSocket = null;
        
        Socket clientSocket = null;
        
        //System.out.println("loc: " + InetAddress.getLocalHost());
        try{
            serverSocket = new ServerSocket(PORT, MAX_QUEUE_LENGTH, InetAddress.getLocalHost());
            serverSocket.setReuseAddress(true);
            System.out.println("Successfully conected");
            while (true){
                clientSocket = serverSocket.accept();
                //System.out.println(clientSocket);
                new ConnectionHandler(clientSocket, booksList);
            }
        } catch (Exception e) {
            /*System.out.println("Error: " + e.getMessage());
            System.out.println("Server shut down");
            System.exit(1);*/
        }
    }
        
    static class ConnectionHandler extends Thread{
        ObjectOutputStream out;
        ObjectInputStream in;
        Socket clientSocket;
        BooksList booksListReference;
        
        public ConnectionHandler(Socket clientSocket, BooksList booksListReference){
            this.clientSocket = clientSocket;
            this.booksListReference = booksListReference;
            start();
        }
        
        void registerBook(Book book){
            booksListReference.insertBook(book);
            try {
                out.close();
            } catch (IOException e) {
                System.out.println("Error");
                System.exit(1);
            }
        }
        
        public void run(){
            try {
                out = new ObjectOutputStream(clientSocket.getOutputStream());
                in = new ObjectInputStream(clientSocket.getInputStream());
                
                Package userPackage = (Package) in.readObject();
                String packageType = userPackage.getType();
                if (packageType.equals("bookRegistration")){
                    Object[] receivedObjects = userPackage.getObjects();
                    Book book = (Book) receivedObjects[0];
                    registerBook(book);
                    System.out.println("Books count: " + booksListReference.getBooksCount());
                }
            } catch (IOException e) {
                System.out.println("Failed to get I/O");
                System.out.println("5");
                e.printStackTrace();
                System.exit(1);
            } catch (ClassNotFoundException e){
                System.out.println("Class not found");
                System.exit(1);
            } finally {
                try {
                    clientSocket.close();
                }
                    catch (IOException e) {
                        System.out.println("Error");
                        System.exit(1);
                }
            }
        }
    }
}
Looking forward for some help

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
Where in your code do you check for a successful connection? What are you trying to connect to? If nothing's listening, you can't connect to it.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
thatsme

thatsme

    Programmer

  • Members
  • PipPipPipPip
  • 176 posts
I am trying to connet client (class Client) to server (class BookStoreServer). I do that with this line in Client class - Socket newClientSocket = new Socket("78.60.65.181", PORT);. I am listening for connection with this line in BookStoreServer class - clientSocket = serverSocket.accept();. Moreover my client successguly connects. If i put line System.out.println("Conected"); in ConnectionHandler constructor, it prints "conected". However when method run() is being run i get exeption in line Package userPackage = (Package) in.readObject();. This exception tells that connection was reset so that means connectionwas set succesfully before being reset.

#4
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
When you printed the InetAddress.getLocalHost(), you got "78.60.65.181", right? Cause your code is working fine with me.

Ahh I finally got the error you got.
I assumed that you got no stacktrace at the client side, so I fixed the errors you had there.

But I bet you got
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Client.main(Client.java:20)
...



Object[] objectsToSend = {};
objectsToSend[0] = book1;
At the first line you create an array of size 0. Meaning you can't put anything in it cause it's too small.
At the next line you try to insert something -> big fail cause the array's too small.

Solution:
Object[] objectsToSend = {""};


OR

Object[] objectsToSend = new Object[1];


Also, why do you use
serverSocket = new ServerSocket(PORT, MAX_QUEUE_LENGTH, InetAddress.getLocalHost());
instead of
serverSocket = new ServerSocket(PORT);
(note it will use localhost, so your client must connect to 127.0.0.1)

If that's your first socket application, the latter would make more sence imo :)

Edited by wim DC, 01 October 2011 - 01:46 AM.


#5
thatsme

thatsme

    Programmer

  • Members
  • PipPipPipPip
  • 176 posts
thanks. that helped




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users