Rede

3 respostas
cu_ringa

estou fazendo um programinha para se comunicar entre computadores, mas não to conseguindo fazer com que, se conecte mas de um cliente ao servidor( meu computador ). Será q é pq estou rodando o programinha( cliente ) mas de uma vez da mesma máquina( tb meu computador) e aí é o mesmo IP, sendo assim o servidor não aceita!!!

há um programinha para fazer a função do cliente e outro q faz a do servidor.

Alguem sabe como devo proceder!!!

3 Respostas

cv1

Cara, nao deu pra entender nada do que vc quis dizer. Posso te pedir pra reformular a pergunta? :smiley:

cu_ringa

Tenho a classe Client_1, Server e Conexao(classe default que esta no mesmo arquivo de Server), mas quando instancio um objeto de Conexao, parece que trava tudo.

Alguem sabe porque???
bora galera, por favor me ajudem, não custa nada é só copiar, colar, compilar e executar para vcs desvendarem o erro. E não se esqueçam q tem que mudar o IP no programa, para o IP de sua máquina!!!

vamos lá conto com vcs, desesperadamente me ajudemmmmmmmmm!!!

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Client_1 extends JFrame implements Runnable{
   private JTextField enter;
   private JTextArea display;
   ObjectOutputStream output;
   ObjectInputStream input;
   String message = "";
	 private Thread outputThread;
	 private Socket connection;
	 
   public Client_1()
   {
      super( "Client" );

      Container c = getContentPane();

      enter = new JTextField();
      enter.setEnabled( true );
      enter.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e )
            {
               sendData( e.getActionCommand() );
               enter.setText("");
               System.out.println(e.getActionCommand());
            }
         }
      );
      c.add( enter, BorderLayout.NORTH );

      display = new JTextArea();
      c.add( new JScrollPane( display ),
             BorderLayout.CENTER );
			
			addWindowListener(
				new WindowAdapter(){
					public void windowClosing(WindowEvent we){
						try{
							//output.writeObject("CLIENT>>> TERMINATE");
							System.exit(0);
							connection.close();
						}
						catch(Exception e){}
					}
				}
			);
			
      setSize( 300, 150 );
      show();
      System.out.println("lua");
   		inicio();
   }
   
	 public void inicio(){
	 				
	 	 try{
	 	 	connection = new Socket(InetAddress.getByName("169.254.117.138"), 5000);
	 	 	input = new ObjectInputStream(connection.getInputStream());
	 	 	output = new ObjectOutputStream(connection.getOutputStream());
	 		System.out.println("carlosbernaco"); 
	 	 }
	 	 catch(IOException e){e.toString();}
	 	 
	 	 System.out.println("lua_1");	 		 	
	 	 
	 	 outputThread = new Thread(this);
	 	 outputThread.start();
	 }
	 
	 public void run(){
	 	
	 	while(true){
	 		try{
	 			String s = (String)input.readObject();
	 			processMessage(s);
	 		}
	 		catch(IOException e){}
	 		catch(ClassNotFoundException cnfex){}
	 	}
	 	
	 } 
	
	 public void processMessage(String s){
	 	
	 	if(!s.equals(""))
	 		display.append(s + '
');
	 		 
	 }
	 
	 private synchronized void sendData( String s )
   {
      try {
         message = s;
         output.writeObject( "CLIENT>>> " + s );
         output.flush();
         display.append( "
CLIENT>>>" + s );
      }
      catch ( IOException cnfex ) {
         display.append(
            "
Error writing object" );
      }
   }
   
   public static void main(String args[]){
   	
   	Client_1 c1 = new Client_1();
   	   	
   }
	 	
}

 





import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Server extends JFrame {
   
   private JTextArea display;
   Conexao conexao[];
	 	 	 
   public Server()
   {
      super( "Server" );

      Container c = getContentPane();
			
			conexao = new Conexao[2];
												
      display = new JTextArea();
      c.add( new JScrollPane( display ),
             BorderLayout.CENTER );
      display.setText("Servidor esperando conexão
");

      setSize( 300, 150 );
      show();
     	
     	execute(); 
   }

	 
	 public void execute()
   {	   		
   		ServerSocket server;
   		Socket connection;
   				    	   		
   		try {
      //for ( int i = 0; i < conexao.length; i++ ) {
      	server = new ServerSocket(5000, 1);
                  		
        display.setText( "Waiting for connection
" );
        connection = server.accept();
            
            display.append( "Connection " + 1 +
               " received from: " +
               connection.getInetAddress().getHostName() );
         		         		
            conexao[ 0 ] =
               new Conexao( connection, 0 );
            System.out.println("solar_2");
            conexao[ 0 ].start();
            System.out.println("solar_3");
            
         }
         catch( IOException e ) {
            e.printStackTrace();
            System.exit( 1 );
         }
         catch(Exception ee){System.out.println("marilia");}
      //}
				
				System.out.println("sol");
      // Player X is suspended until Player O connects.
      // Resume player X now.          
     /*
      synchronized ( conexao[ 0 ] ) {
         System.out.println("sol_1");
         conexao[ 0 ].threadSuspended = false;   
         conexao[ 0 ].notify();
      }*/
  
   }
   
   
   public void display( String s )
   {
      display.append( s + "
" );
   }
	 
	 	 
   public static void main( String args[] )
   {
      Server app = new Server();

      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               System.exit( 0 );
            }
         }
      );

     
   }
}


class Conexao extends Thread {
   private Socket connection;
   private ObjectInputStream input;
   private ObjectOutputStream output;
   private Server control;
   private int number;
   protected boolean threadSuspended = true;

   public Conexao( Socket s, int num )
   {
     connection = s;
//     control = t;
     number = num;
                   
      try {
         input = new ObjectInputStream(
                    connection.getInputStream() );
         output = new ObjectOutputStream(
                    connection.getOutputStream() );
      }
      catch( IOException e ) {
         e.printStackTrace();
         System.exit( 1 );
      }
			      
     // control.display( "
Got I/O streams
" );
      System.out.println("solar_2001");
   }


   public void run()
   {
      boolean done = false;

      try {
         
         // wait for another player to arrive
         if ( number == 0 ) {
           
            try {
               synchronized( this ) {
               	System.out.println("sol_2");   
                  while ( threadSuspended )
                     wait();  
               }
            } 
            catch ( InterruptedException e ) {
               e.printStackTrace();
            }

            output.writeObject(
               "Other player connected. Your move." );
         }

			}
			catch ( IOException e ) {
               e.printStackTrace();
            }
		}
}
cu_ringa

consegui a conexão galera, agora está dando o seguinte problema:

eu rodo o programinha servidor e rodo o programinha cliente 2 vezes, ou seja tenho 2 clientes conectados ao servidor.

No prgraminha servidor tem um ObjectOutputStream output, quando chamo o metodo writeObject de output, exemplo:

String s = input.readObject();
output.writeObject(s);

só ocorre atualização no último cliente q foi conectado, pqserá q tá acontecendo isso!!!

Criado 31 de janeiro de 2004
Ultima resposta 1 de fev. de 2004
Respostas 3
Participantes 2