Eu estou tentando construir uma aplicação socket multiusuario até funciona quando eu DataInputStream e
DataOutputStream mas quando eu tendo serializar com objectInputSteram e ObjectOutPutStream a aplicação
Trava .Meu Codigo e seguinte.
Cliente[code]
public class ClienteSocket {
public int soma(int n1, int n2) {
// TODO Auto-generated method stub
int soma = 0;
try {
Socket socket=new Socket("localhost",4444);
ObjectInputStream entrada = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream saida = new ObjectOutputStream(socket.getOutputStream());
saida.writeInt(n1);
saida.writeInt(n2);
soma=entrada.readInt();
saida.flush();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return soma;
}
}[/code]
Servidor
[code]public class SocketSoma {
private final Socket socket;
public SocketSoma(Socket socket) {
this.socket=socket;
}
public void Soma() {
try {
ObjectInputStream entrada = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream saida = new ObjectOutputStream(socket.getOutputStream());
int n1=entrada.readInt();
int n2=entrada.readInt();
saida.writeInt(n1+n2);
saida.flush();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
[/code]
Eu tenho tenho classe que rodano console que instancia serverSocket e inicia a Thread
[code]public class Servidor {
public static void main(String[] args) {
try {
ServerSocket servidor=new ServerSocket(4444);
System.out.println("Servidor aguardado conexões .Porta "+servidor.getLocalPort());
while(true){
final Socket socket=servidor.accept();
new Thread(){
public void run(){
new SocketSoma(socket).Soma();
}
}.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
[/code]
E um cliente swing que instancia o socket tambem em uma thread:
public class Cliente extends JFrame {
public Cliente() {
super("Cliente Socket");
Container painel = getContentPane();
final JTextField n1 = new JTextField(5);
final JTextField n2 = new JTextField(5);
JButton ok = new JButton("Somar");
final JTextArea area = new JTextArea(30,30);
painel.setLayout(new FlowLayout());
painel.add(n1);
painel.add(n2);
painel.add(ok);
painel.add(area);
ok.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
new Thread(){
public void run(){
String s1=n1.getText();
String s2=n2.getText();
int soma=new ClienteSocket().soma(Integer.parseInt(s1),Integer.parseInt(s2));
area.append("Soma("+s1+"+"+s2+"): "+soma+"\n");
}
}.start();
}
});
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Cliente frame=new Cliente();
frame.setVisible(true);
frame.setSize(400,300);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
} );
}
}
agradeço qualquer ajuda.