套接字编程:连接重置异常 - Java

时间:2013-09-26 15:59:45

标签: java sockets connection socketexception

我正在尝试从远程服务器读取数据的程序(我无法访问服务器代码)并打印它。 当我使用方法InputStream.read()时它崩溃,抛出这个异常:java.net.SocketException:Connection reset

这是我的代码:

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();*/
        }

    }
}

1 个答案:

答案 0 :(得分:0)

服务器已重置连接。也许你应该在接收之前发送一些东西?