Ir ao conteúdo
  • Cadastre-se

Problema ao enviar e receber objeto por socket


redhorse

Posts recomendados

ERRO java.io.StresamCorruptedStreamException: invalid type code: AC

 

O que estou tentando fazer?

Eu quero que o servidor apos fazer uma consulta do DB, envie os objetos para o cliente e este preencha uma tabela com as informações contidas nos objetos.

tenei de varias formas, essa é uma delas, o erro esta acima, trechos do codigo:

 

SERVIDOR..

PrintStream saida = new PrintStream(conexao.getOutputStream());            ObjectOutputStream output = new ObjectOutputStream(conexao.getOutputStream());            ObjectInputStream input = new ObjectInputStream(conexao.getInputStream());....ResultSet RS = stmt.executeQuery(query);                            if (!RS.next()) {                                System.out.println("Nenhum registro foi encontrado com essa pesquisa!");                            } else {                                                                Vector<Cliente> c = new Vector<Cliente>();                                RS.beforeFirst();                                while (RS.next()) {                                    c.add(new Cliente(RS.getString("nome"), RS.getString("fone")));                                }                                ObjectOutputStream oo = new ObjectOutputStream(saida);                                 oo.writeObject(c);                                oo.close();
CLIENTE ..

entrada = new BufferedReader(new InputStreamReader(conexao.getInputStream()));            saida = new PrintStream(conexao.getOutputStream());            output = new ObjectOutputStream(conexao.getOutputStream());            input = new ObjectInputStream(conexao.getInputStream());...ObjectInputStream oi = new ObjectInputStream(input)             Cliente c = (Cliente) oi.readObject();                        System.out.println(c.getNome() + " " + c.getFone());
Link para o comentário
Compartilhar em outros sites

Amigo, poste um código completo simulando o seu problema para que possamos ajudar.

 

Olhando para o código postado o único possível problema que pude notar é que você está usando o mesmo InputStream para um BufferedReader e um ObjectInputStream.

 

Editado

 

Criei um pequeno exemplo de como trabalhar com a serialização e envio de objetos usando Socket, segue abaixo o código.

import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.net.ServerSocket;import java.net.Socket;import java.util.Date;import java.util.Vector;public class Main {	public static void main(String[] args) {		new Thread(new Server()).start();		new Thread(new Client()).start();	}		static class Client implements Runnable {		public void run() {						try {								System.out.println("Inciando o cliente");								Socket socket = new Socket("localhost", 9999);				ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());				System.out.println("Recebendo lista de coisas");				Vector<Thing> things = (Vector<Thing>) inputStream.readObject();				for (Thing thing : things) {					System.out.println(thing);				}								socket.close();							} catch (Exception e) {				e.printStackTrace();			}								}	}	static class Server implements Runnable {		public void run() {			try {								System.out.println("Iniciando o servidor");								ServerSocket serverSocket = new ServerSocket(9999);				Socket socket = serverSocket.accept();								System.out.println("Client conectado");								ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());								System.out.println("Enviando lista de coisas");				outputStream.writeObject(getThingVector());								outputStream.close();				serverSocket.close();							} catch (Exception e) {				e.printStackTrace();			}		}				private Vector<Thing> getThingVector() {			Vector<Thing> things = new Vector<Main.Thing>();			for (int i = 0; i < 100; i++) {				things.add(new Thing(i, "Thing" + i, new Date()));			}						return things;		}	}	static class Thing implements Serializable {		private static final long serialVersionUID = 7639521599393469721L;			private int id;		private String name;		private Date creationDate;		public Thing(int id, String name, Date creationDate) {			this.id = id;			this.name = name;			this.creationDate = creationDate;		}		public int getId() {			return id;		}				public String getName() {			return name;		}		public void setName(String name) {			this.name = name;		}		public Date getCreationDate() {			return creationDate;		}		public void setCreationDate(Date creationDate) {			this.creationDate = creationDate;		}		@[member=override]		public String toString() {			return "Thing [id=" + id + ", name=" + name + ", creationDate=" + creationDate + "]";		}	}}
Link para o comentário
Compartilhar em outros sites

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...