0

I'm trying to do a program that reads data from a remote server (I don't have access to the server code) and prints it. It crashes when I use the method InputStream.read(), throwing me this exception: java.net.SocketException: Connection reset

Here is my code:

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;


public class ProtocoloX {
    private byte[] bytes = new byte[1024];
    //private byte[] bytes = new byte[]{(byte) 0xC6, 0x57, 0x54, (byte) 0x95, 0x5E, (byte) 0x9E, 0x6B, (byte) 0xC6, 0x55, 0x17, 0x55,0x52, (byte) 0x9E, 0x21};
    private Socket cliente;
    private final String HOST = "177.71.195.77";
    private final int PORT = 56668;

    public boolean connect(){
        this.cliente = new Socket();
        System.out.println("-- Trying to connect: "+HOST+":"+PORT);
        InetSocketAddress socketAddress = new InetSocketAddress(HOST, PORT); 
        try {
            this.cliente.connect(socketAddress, 10000000);
        } catch (IOException e) {
            System.out.println(e);
            System.out.println("-- CONNECTION PROBLEM ");
            return false;
        }

        System.out.println("-- Connection successful");
        return true;
    }

    private void receive(){
        InputStream stream = null;  
        System.out.println("-- Reading data...");
        try {
            stream = this.cliente.getInputStream();
            try {
                int count = stream.read();
                System.out.println((char) count);
            } catch (IOException e) {
                System.out.println("-- DATA READING PROBLEM");
                e.printStackTrace();
            }
        } catch (IOException e) {
            System.out.println("-- DATA READING PROBLEM");
            e.printStackTrace();
        }
        System.out.println("-- Data read successful");
    }

    private void send(){
        //TODO: função que envia sinal
    }

    private void decode(){

    }

    private void encode(){
        //TODO: função que codifica
    }

    public static void main(String[] args) throws UnknownHostException, IOException {
        ProtocoloX protocolo = new ProtocoloX();
        if(protocolo.connect()){
            protocolo.receive();
            /*protocolo.decode();
            protocolo.encode();
            protocolo.send();*/
        }

    }
}
  • Have a look at these two threads - http://stackoverflow.com/questions/585599/whats-causing-my-java-net-socketexception-connection-reset and http://stackoverflow.com/questions/62929/java-net-socketexception-connection-reset – Ankit Sep 26 '13 at 16:06

1 Answers1

0

The server has reset the connection. Maybe you were supposed to send it something before receiving?

user207421
  • 305,947
  • 44
  • 307
  • 483