fiz um pequeno programa de rede estilo aqueles que tem no “core java”( para 2 ou mais clientes se conectarem simutâneamente ao servidor), só que quando o servidor( programinha servidor ) manda uma mensagem para os clientes( prgraminha cliente ), so atualiza o último cliente( programinha cliente ) que se conectou.
Alguém sabe como posso solucionar esse problema é esse?
quando eu falo programinha cliente e servidor é q se vcs virem no deitel ou no core java, para um programa de rede ele tem a parte cliente( um programa cliente ) e uma parte servidor( programa servidor ).
olhe o código aí. Quando eu executo a classe Client_1 2 vezes cada uma(classe Client_1) faz sua conexao ao servidor( Classe Server ) e seu metodo run(classe Client_1), fica executando esperando algum texto do servidor, entao quando servidor manda um texto atraves do metodo output.writeObject() eu acho q era para atualizar nas duas classes Client_1, mas só atualiza na classe que se conectou por último ao servidor.
Será q alguém sabe o q está acontecendo???
<— por favor me ajudem —>
Classe Client_1
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.getLocalHost(), 5000 );
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
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();
System.out.println("s = " + s);
processMessage(s);
}
catch(IOException e){}
catch(ClassNotFoundException cnfex){}
}
}
public void processMessage(String s){
display.append(s + '\n');
}
private synchronized void sendData( String s )
{
try {
message = s;
output.writeObject( "CLIENT>>> " + s );
output.flush();
//display.append( "\nCLIENT>>>" + s );
}
catch ( IOException cnfex ) {
display.append(
"\nError writing object" );
}
}
public static void main(String args[]){
Client_1 c1 = new Client_1();
}
}
Classe Server e classe Conexao
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 con;
JTextField enter;
public Server()
{
super( "Server" );
Container c = getContentPane();
enter = new JTextField();
enter.setEnabled( true );
enter.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent e )
{
con.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 );
setSize( 300, 150 );
show();
}
public void execute()
{
ServerSocket server;
Socket connection;
int i = 0;
try {
server = new ServerSocket(5000);
display.setText( "Servidor esperando conexão\n" );
while(true){
connection = server.accept();
display.append( "Connection " + i +
" received from: " +
connection.getInetAddress().getHostName() + '\n');
con = new Conexao( connection, i++ );
con.start();
System.out.println("solar_2");
System.out.println("solar_3");
}
}
catch( IOException e ) {
e.printStackTrace();
System.exit( 1 );
}
catch(Exception ee){System.out.println("marilia");}
System.out.println("sol");
}
public static void main( String args[] )
{
Server app = new Server();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
app.execute();
}
}
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() );
System.out.println("solar_2014");
output = new ObjectOutputStream(
connection.getOutputStream() );
output.writeObject("Conectado com sucesso!!!\n");
}
catch( IOException e ) {
e.printStackTrace();
System.exit( 1 );
}
// control.display( "\nGot I/O streams\n" );
System.out.println("solar_2001");
}
public void run(){
while(true){
try{
String s = (String)input.readObject();
System.out.println("s = " + s);
sendData(s);
output.flush();
//processMessage(s);
}
catch(IOException e){}
catch(ClassNotFoundException cnfex){}
}
}
protected synchronized void sendData( String s )
{
try {
//message = s;
output.writeObject(s);
output.flush();
//display.append( "\nCLIENT>>>" + s );
}
catch ( IOException cnfex ) {
// display.append(
// "\nError writing object" );
}
}
}
Dei uma rápida olhada no teu código, pelo que eu vi, vc está criando objetos con… Talvez um está sobrescrevendo outro… Tente utilizar um array de Conexões, desse modo vc terá como controlar todas as conexões no teu servidor
Vou fazer alguns testes assim que puder… e posto o resultado aqui…