Bom dia pessoal… estou com um problema, o codigo abaixo so permite que um cliente se comunique com o servidor, queria torna-lo um ambiente multithread,sem perder a caracteristica de que o servidor possa enviar mensagens para todos os clientes. Eu tentei ja colocar runnable,thread , so que sempre da erro quando vou executar mais de um cliente, alguem sabe como posso adequar esse codigo para multithread? minhas solucoes nao deram certo…
segue o codigo abaixo
========================================================
Classe Servidor
package Sockets;
import <a href="http://java.io">java.io</a>.<em>;
import <a href="http://java.net">java.net</a>.</em>;
import java.awt.<em>;
import java.awt.event.</em>;
import javax.swing.*;
public class Server extends JFrame {
private JTextField enter;
private JTextArea display;
ObjectOutputStream output;
ObjectInputStream input;
public Server() {
super("Server");
Container c = getContentPane();
enter = new JTextField();
enter.setEnabled(false);
enter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendData(e.getActionCommand());
}
});
c.add(enter, BorderLayout.NORTH);
display = new JTextArea();
c.add(new JScrollPane(display), BorderLayout.CENTER);
setSize(300, 150);
show();
}
public void runServer() {
ServerSocket server;
Socket connection;
int counter = 1;
try {
// Step 1: Criar Servidor socket
server = new ServerSocket(5050, 100);
while (true) {
// Step 2: Esperando a conexao
display.setText("Esperando a Conexao\n");
connection = server.accept();
display.append("Connection " + counter + " received from: "
+ connection.getInetAddress().getHostName());
// Step 3: Get input and output streams.
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
display.append("\nGot I/O streams\n");
// Step 4: Processando Conexao.
String message = "SERVER>>> Connection successful";
output.writeObject(message);
output.flush();
enter.setEnabled(true);
do {
try {
message = (String) input.readObject();
display.append("\n" + message);
display.setCaretPosition(display.getText().length());
} catch (ClassNotFoundException cnfex) {
display.append("\nUnknown object type received");
}
} while (!message.equals("CLIENT>>> TERMINATE"));
// Step 5: Fechar Conexao
display.append("\nUser terminated connection");
enter.setEnabled(false);
output.close();
input.close();
connection.close();
++counter;
}
} catch (EOFException eof) {
System.out.println("Client terminated connection");
} catch (IOException io) {
io.printStackTrace();
}
}
private void sendData(String s) {
try {
output.writeObject("SERVER>>> " + s);
output.flush();
display.append("\nSERVER>>>" + s);
} catch (IOException cnfex) {
display.append("\nError writing object");
}
}
public static void main(String args[]) {
Server app = new Server();
app.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
app.runServer();
}
}
=======================================================
Classe Cliente
package Sockets;
import <a href="http://java.io">java.io</a>.<em>;
import <a href="http://java.net">java.net</a>.</em>;
import java.awt.<em>;
import java.awt.event.</em>;
import javax.swing.*;
public class Client extends JFrame {
private JTextField enter;
private JTextArea display;
ObjectOutputStream output;
ObjectInputStream input;
String message = “”;
public Client() {
super("Client");
Container c = getContentPane();
enter = new JTextField();
enter.setEnabled(false);
enter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendData(e.getActionCommand());
}
});
c.add(enter, BorderLayout.NORTH);
display = new JTextArea();
c.add(new JScrollPane(display), BorderLayout.CENTER);
setSize(300, 150);
show();
}
public void runClient() {
Socket client;
try {
// Step 1: Criar Socket para fazer conexao.
display.setText("Attempting connection\n");
client = new Socket(InetAddress.getByName("127.0.0.1"), 5050);
display.append("Connected to: "
+ client.getInetAddress().getHostName());
// Step 2: Get the input and output streams.
output = new ObjectOutputStream(client.getOutputStream());
output.flush();
input = new ObjectInputStream(client.getInputStream());
display.append("\nGot I/O streams\n");
// Step 3: Processar Conexao.
enter.setEnabled(true);
do {
try {
message = (String) input.readObject();
display.append("\n" + message);
display.setCaretPosition(display.getText().length());
} catch (ClassNotFoundException cnfex) {
display.append("\nUnknown object type received");
}
} while (!message.equals("SERVER>>> TERMINATE"));
// Step 4: Fechar Conexao
display.append("Closing connection.\n");
output.close();
input.close();
client.close();
} catch (EOFException eof) {
System.out.println("Server terminated connection");
} catch (IOException e) {
e.printStackTrace();
}
}
private 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 app = new Client();
app.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
app.runClient();
}
}