Parowanie Klientów - Klient Serwer

0

Witam napisałem na socketach prostą aplikację czat, teraz chcę to przerobić na grę karcianą oczko z czatem. W gre mogą grac jednocześnie dwie osoby jednak jeśli na serwerze będzie 8 osób chce żeby były cztery gry.
Jak parować klientów oraz jak zapewnić im komunikację.
gdzie mogę znaleźć jakieś ciekawe artykuły bądź pomoce na ten temat.

0

Tutaj macie kod czat działa , otworzyłem serwer na nowym porcie dla obslugi gry ale nie wiem jak zadbac o parowanie klientow jakies propozycje , wgle jak to ruszyć dalej?

public class Connection {
    private Socket socket;
    private DataInputStream in;
    private DataOutputStream out;
    
    
    public Connection() throws IOException{
        socket = new Socket("localhost", 7777);
        in = new DataInputStream(socket.getInputStream());   
        out = new DataOutputStream(socket.getOutputStream());
    }
    
    public String getString() throws IOException{
        String test = in.readUTF();
        return test;       
    }
    
    public DataInputStream getInput(){
        return this.in;
    }
    
    public DataOutputStream getOutput(){
        return this.out;
    }

}














package oczkosocket.serwer;
import java.io.DataOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import oczkosocket.karta.*;
/**
 *
 * @author rafal
 */
public class Server {
    static ServerSocket serverSocket;
    static ServerSocket gameSocket;
    static Socket socket;
    static Socket gSocket;
    static DataOutputStream out;
    static Users[] user = new Users[10];
    static DataInputStream in;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        System.out.println("Starting server..."); 
        serverSocket = new ServerSocket(7777);
        gameSocket = new ServerSocket(2222);
        System.out.println("Server started...");    
        while(true){      
            socket = serverSocket.accept();
            for(int i = 0;i < 10; i++){    
                out = new DataOutputStream(socket.getOutputStream());
                in = new DataInputStream(socket.getInputStream());
                if(user[i] == null){   
                    System.out.println("Connection from:" + socket.getInetAddress());
                    user[i] = new Users(out,in,user);    
                    Thread thread = new Thread(user[i]);    
                    thread.start();
                    break;    
                }    
            }  
            gSocket = gameSocket.accept();
        } 
    }
    
}

class Users implements Runnable{
    
        DataOutputStream out;
        DataInputStream in;  
        Users[] user = new Users[10];
        public Users(DataOutputStream out, DataInputStream in, Users[] user)
        {   
            this.out = out;
            this.in = in;   
            this.user = user;  
        }
    @Override
    public void run() {
         while(true){   
                try 
                {     
                String message = in.readUTF();
                for (int i = 0;i < 10; i++)
                    {     
                    if(user[i]!= null)
                    {      
                        user[i].out.writeUTF(message);
                    }        
                    }     
                }    
        catch (IOException e) {}       
            } 
    }
    
    

}







package oczkosocket.klient;
import oczkosocket.karta.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

/**
 *
 * @author rafal
 */
public class GameConnection {
    private Socket socket;
    private DataInputStream in;
    private DataOutputStream out;
    
    
    public GameConnection() throws IOException{
        socket = new Socket("localhost", 2222);
        in = new DataInputStream(socket.getInputStream());   
        out = new DataOutputStream(socket.getOutputStream());
    }
    
    
    public DataInputStream getInput(){
        return this.in;
    }
    
    public DataOutputStream getOutput(){
        return this.out;
    }

}















/*
 * 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 oczkosocket.klient;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.DefaultCaret;
import oczkosocket.karta.*;
/**
 *
 * @author rafal
 */
public class OczkoKlient extends javax.swing.JFrame {

    /**
     * Creates new form OczkoKlient
     */
    
    
    
   
    public OczkoKlient() throws IOException {
        initComponents();
    }
    
    

    /**
     * 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();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jTextField2 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();
        graj = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea2 = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

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

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jLabel1.setText("Tutaj podaj nick:");

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

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

        jLabel3.setText("Suma:");

        jLabel5.setText("0");

        jButton3.setText("Dobierz karte");

        graj.setText("Graj");
        graj.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                grajActionPerformed(evt);
            }
        });

        jTextArea2.setColumns(20);
        jTextArea2.setRows(5);
        jScrollPane2.setViewportView(jTextArea2);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(graj, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 126, Short.MAX_VALUE)
                        .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jButton2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGap(6, 6, 6)
                            .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 505, Short.MAX_VALUE)
                    .addComponent(jTextField2)
                    .addComponent(jScrollPane2)))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(graj, javax.swing.GroupLayout.DEFAULT_SIZE, 72, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jLabel5)))
                    .addComponent(jScrollPane2))
                .addGap(29, 29, 29))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

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

    private void Polacz(java.awt.event.ActionEvent evt) {                        
        try {
            // TODO add your handling code here:
            if(this.con == null){
            String nick = jTextField1.getText();
            if(nick.equals(""))
            {
                jTextArea1.append("Musisz podac nick , sproboj ponownie\n");
            }
            else{
            String nickk = jTextField1.getText();
            this.nick = nickk;
            jTextField1.setEditable(false);
            Connection con = new Connection();
            Input input = new Input(con.getInput());
            Thread thread = new Thread(input);
            this.con = con;
            thread.start(); 
            }
            }
            else{
                jTextArea1.append("Jestes juz polaczony\n");
            }
        } catch (IOException ex) {
            Logger.getLogger(OczkoKlient.class.getName()).log(Level.SEVERE, null, ex);
        }     
        
    }                       
class Input implements Runnable{
    
    
    DataInputStream in;
    public Input(DataInputStream in)
    {   this.in = in;
    }  
    public void run()
    {   while(true){    
        String message;    
        try{     
            message = in.readUTF();
            DefaultCaret caret = (DefaultCaret)jTextArea1.getCaret();
            caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
            jTextArea1.append(message + "\n");
        }catch(IOException e){     
            e.printStackTrace();    
        }       
    }  
    }
    
}    
    
    private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    }                                           

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        String message = jTextField2.getText();
        if(con != null){
        try {            
            con.getOutput().writeUTF(nick + ": " + message);
        } catch (IOException ex) {
            Logger.getLogger(OczkoKlient.class.getName()).log(Level.SEVERE, null, ex);
        }
        }
        else{
            jTextArea1.append("Musisz sie najpierw polaczyc");
        }
    }                                        

    private void grajActionPerformed(java.awt.event.ActionEvent evt) {                                     
        if(gameCon == null){
            try {
                GameConnection gcon;
                gcon = new GameConnection();
                jTextArea1.append("Czekam na gracza \n");
                this.gameCon = gcon;
            } catch (IOException ex) {
                Logger.getLogger(OczkoKlient.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }                                    

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) throws IOException {
        /* 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(OczkoKlient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(OczkoKlient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(OczkoKlient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(OczkoKlient.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() {
                try {
                    new OczkoKlient().setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(OczkoKlient.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });        
        
        
    }
    private String nick;
    private Connection con;
    private GameConnection gameCon;
    // Variables declaration - do not modify                     
    private javax.swing.JButton graj;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextArea jTextArea2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration                   
}

1 użytkowników online, w tym zalogowanych: 0, gości: 1