Conexão com Sockets em Java

3 respostas
programaçãojava
Helder_Cavalcante

Olá, Estou começando a trabalhar com sockets em Java, e no momento estou tendo problemas na criação de um chat / jogo da velha online. Consegui estabelecer uma conexão e trabalhar com o chat tranquilamente, porém, ao iniciar o jogo da velha, tenho tido problemas. Pois quando marco X em um dos botões, o botão equivalente do outro usuário online não é marcado corretamente. Gostaria de saber se existe alguma forma de especificar qual botão será marcado com X no outro chat online, Segue meus códigos abaixo:

Pacote cliente:
Classe JogoDaVelha:

package cliente;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintStream;

import java.net.Socket;

import java.util.ArrayList;

import javax.swing.*;

import static javax.swing.JOptionPane.ERROR_MESSAGE;

import static javax.swing.JOptionPane.showMessageDialog;

public class jogoDaVelha extends javax.swing.JFrame {

private String nome;
private Socket s;
private BufferedReader br;
private InputStreamReader isr;
private boolean rodar;
public int position;

public jogoDaVelha() {
    initComponents();
    try {
        Cliente c = new Cliente();
        s = new Socket(c.ip, 5000);
    } catch (Exception e) {
        showMessageDialog(null, "Não foi possível se conectar ao servidor", "", ERROR_MESSAGE);
        System.exit(0);
    }
    Thread();
}

private void Thread() {
    Thread t = new Thread(new Runnable() {
        // String mensagem;

        @Override
        public void run() {

            runTryCatch(jButton1, 1);
            runTryCatch(jButton2, 2);
            runTryCatch(jButton3, 3);
            runTryCatch(jButton4, 4);
            runTryCatch(jButton5, 5);
            runTryCatch(jButton6, 6);
            runTryCatch(jButton7, 7);
            runTryCatch(jButton8, 8);
            runTryCatch(jButton9, 9);

        }

    });
    t.start();
}

private void runTryCatch(JButton btn, int pos) {
    String mensagem;
    try {
        position = pos;
        isr = new InputStreamReader(s.getInputStream());
        br = new BufferedReader(isr);

        while ((mensagem = br.readLine()) != null) {

            btn.setText(mensagem + " " + position);

            if (!rodar) {
                break;
            }

        }
    } catch (IOException e) {
        showMessageDialog(null, "Erro de conexão com o servidor", "", ERROR_MESSAGE);
    }
}

private void setBTN(JButton btn, int pos) {
    position = pos;
    btn.setText("X");
    try {
        PrintStream ps = new PrintStream(s.getOutputStream());

        ps.println("X");
        ps.flush();
    } catch (IOException e) {
        showMessageDialog(null, "Mensagem não enviada", "", ERROR_MESSAGE);

    }
}

private void JButtonArray() {
    ArrayList<JButton> botoes = null;
    botoes.add(jButton1);
    botoes.add(jButton2);
    botoes.add(jButton3);
    botoes.add(jButton4);
    botoes.add(jButton5);
    botoes.add(jButton6);
    botoes.add(jButton7);
    botoes.add(jButton8);
    botoes.add(jButton9);

}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jButton4 = new javax.swing.JButton();
    jButton5 = new javax.swing.JButton();
    jButton6 = new javax.swing.JButton();
    jButton7 = new javax.swing.JButton();
    jButton8 = new javax.swing.JButton();
    jButton9 = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }
    });

    jButton4.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton4ActionPerformed(evt);
        }
    });

    jButton5.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton5ActionPerformed(evt);
        }
    });

    jButton6.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton6ActionPerformed(evt);
        }
    });

    jButton7.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton7ActionPerformed(evt);
        }
    });

    jButton8.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton8ActionPerformed(evt);
        }
    });

    jButton9.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton9ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 87, Short.MAX_VALUE))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, 99, Short.MAX_VALUE)
                        .addComponent(jButton7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGap(18, 18, 18)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jButton9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
            .addGap(40, 40, 40))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE))
            .addGap(18, 18, 18)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton6, javax.swing.GroupLayout.DEFAULT_SIZE, 65, Short.MAX_VALUE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(jButton7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton9, javax.swing.GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE)))
    );

    jLabel1.setText("SCORE");

    jLabel2.setText("SCOREVALUE");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addContainerGap())
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(29, 29, 29)
            .addComponent(jLabel2)
            .addGap(73, 73, 73))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel2))
            .addGap(20, 20, 20))
    );

    pack();
}// </editor-fold>                        

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    setBTN(jButton1, 1);

}                                        

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    setBTN(jButton2, 2);


}                                        

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    setBTN(jButton3, 3);

}                                        

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    setBTN(jButton4, 4);

}                                        

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    setBTN(jButton5, 5);

}                                        

private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    setBTN(jButton6, 6);

}                                        

private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    setBTN(jButton7, 7);

}                                        

private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    setBTN(jButton8, 8);

}                                        

private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    setBTN(jButton9, 9);

}                                        

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(jogoDaVelha.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(jogoDaVelha.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(jogoDaVelha.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(jogoDaVelha.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new jogoDaVelha().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
private javax.swing.JButton jButton9;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
// End of variables declaration

}


pacote Servidor
classe jogoDaVelhaSockets:
/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package servidor;
import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintStream;

import java.net.Socket;

import java.util.ArrayList;

/**
*

  • @author hdrhe
    */
    public class jogoDaVelhaSockets {

    private Socket s;

//Setters

public jogoDaVelhaSockets(Socket s) {
    this.s = s;
   
    Thread_();
}

private void Thread_() {
    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
             
            try {
                InputStreamReader isr = new InputStreamReader(s.getInputStream());

                BufferedReader br = new BufferedReader(isr);

                 
                    System.out.println(br.readLine());
                 
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

t.start();
}

//    private void enviarMensagem(String mensagem) {

//        for (int a = 0; a < clientes.size(); a++) {

//            clientes.get(a).println(mensagem);

//            clientes.get(a).flush();

//        }

//

}

classe Servidor
package servidor;

import <a href="http://java.net">java.net</a>.*;

import java.io.IOException;

import java.io.PrintStream;

import java.util.ArrayList;

public class Servidor {

public static void main(String[] args) {
    ArrayList<PrintStream> clientes = new ArrayList<>();
    String btn1;
    PrintStream print_btn1;
    try {
        ServerSocket server = new ServerSocket(5000);
        Socket socket;
        //Socket socket_btn1;

        while (true) {
            socket = server.accept();
           // socket_btn1 = server.accept();
            //Guarda o endereço do cliente
            clientes.add(new PrintStream(socket.getOutputStream()));
           // print_btn1 = new PrintStream(socket_btn1.getOutputStream());
            Mensagem mensagem = new Mensagem(socket, clientes);
          jogoDaVelhaSockets jgds = new jogoDaVelhaSockets(socket);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

3 Respostas

darlan_machado

Em um jogo da velha, cada botão corresponde a uma posição que representa uma combinação entre linha e coluna da matriz que o jogo representa. Logo, se você marcar o X da linha 0 coluna 2, precisa dizer a todos os envolvidos que aquele botão (posição) foi clicado.
Com isso, creio que você já entendeu como fazer.

Helder_Cavalcante

Estava pesquisando como fazer, decido testar com ByteArrayOutputStream / ByteArrayInputStream, porém não sei exatamente como pegar a informação do lado do servidor, se puder ajudar, segue o código:

Cliente:

public JogoDaVelha() {

initComponents();

this.nome = nome;

imgBtn = new ImageIcon(C:\Users\amorimhe\Desktop\APS 5 Semestre\Cliente\build\classes\cliente\arvore.png);

imgBtn2 = new ImageIcon("/cliente/serra.jpg");

try {

Cliente c = new Cliente();

s = new Socket(c.ip, 5000);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream output = new ObjectOutputStream(baos);

        baos = new ByteArrayOutputStream();
        output = new ObjectOutputStream(baos);
        output.writeObject(matrizA);
        output.flush();
        baos.writeTo(s.getOutputStream());
        baos.flush();
    } catch (Exception e) {
        showMessageDialog(null, "Não foi possível se conectar ao servidor", "", ERROR_MESSAGE);
        System.exit(0);

    }
    Thread();

}
Servidor:

private void Thread_() {

Thread t = new Thread(new Runnable() {
@Override
        public void run() {

            try {
                InputStreamReader isr = new InputStreamReader(s.getInputStream());

                BufferedReader br = new BufferedReader(isr);

                System.out.println("Teste");
                s.getInputStream().read();
                
                bais = new ByteArrayInputStream(s.getInputStream());
                ois = new ObjectInputStream(bais);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    t.start();
}

Consta erro em s.getInputStream(), atestando que InputStream não pode ser convertido para byte, sabe oq posso fazer?

staroski

ByteArrayInputStream é uma classe utilizada para você obter um InputStream através de um array de bytes (um objeto do tipo byte[]), que não é o seu caso.

Ao invés de instanciar o seu ObjectInputStream assim:

bais = new ByteArrayInputStream(s.getInputStream());
ois = new ObjectInputStream(bais)

Instancie assim:

ois = new ObjectInputStream(s.getInputStream());

No seu cliente também não vejo necessidade do ByteArrayOutputStream.
Essa classe serve para você conseguir obter um array de bytes após gravar conteúdo em um OutputStream.

Então o código abaixo:

baos = new ByteArrayOutputStream();
output = new ObjectOutputStream(baos);
output.writeObject(matrizA);
output.flush();
baos.writeTo(s.getOutputStream());
baos.flush();

Pode ser reescrito assim:

output = new ObjectOutputStream(s.getOutputStream());
output.writeObject(matrizA);
output.flush();
Criado 5 de maio de 2019
Ultima resposta 9 de mai. de 2019
Respostas 3
Participantes 3