Pessoal, eu fiz (copiei de um livro) um chat em java... é tipo um messenger.
Tem A classe Server/Server Test (onde roda) e Client/Client Test.
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Client extends JFrame {
private JTextField enterField;
private JTextArea displayArea;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String chatServer;
private Socket client;
//inicializa chatServer e configura a GUI
public Client(String host) {
super("Cliente");
chatServer = host;
enterField = new JTextField();
enterField.setEditable(false);
enterField.addActionListener(
new ActionListener() {
//envia a mensagem ao servidor
public void actionPerformed (ActionEvent event)
{
sendData(event.getActionCommand());
enterField.setText("");
}
}
);
add(enterField, BorderLayout.NORTH);
displayArea = new JTextArea();
add(new JScrollPane(displayArea), BorderLayout.CENTER);
setSize(300,150);
setVisible(true);
}
//conecta-se ao servidor e processa as mensagens a partir do servidor
public void runClient()
{
try //conecta-se ao servidor,obtém fluxos, processa a conexão
{
connectToServer();
getStreams();
processConnection();
}
catch (EOFException eofException)
{
displayMessage("\nClient terminated connection");
}
catch(IOException ioException) {
ioException.printStackTrace();
}
finally
{
closeConnection();
}
}
//conecta-se ao servidor
private void connectToServer() throws IOException {
displayMessage("Attemping connection\n");
client = new Socket(InetAddress.getByName(chatServer), 12345);
displayMessage("\Connected to: " + client.getInetAddress().getHostName());
}
//obtém fluxos para enviar e receber dados
private void getStreams() throws IOException
{
output = new ObjectOutputStream(client.getOutputStream());
output.flush();
input = new ObjectInputStream(client.getInputStream());
displayMessage("\nGot I/O streams\n");
}
//processa a conexão com o servidor
private void processConnection() throws IOException {
setTextFieldEditable(true);
do //processa as mensagens enviadas do servidor
{
try //le e exibe a mensagem
{
message = (String) input.readObject();
displayMessage("\n+ message");
}
catch (ClassNotFoundException classNotFoundException)
{
displayMessage("\nUnknown objetct type received");
}
} while (!message.equals("SERVER>>> TERMINATE"));
}
//fecha os fluxos e o socket
private void closeConnection() {
displayMessage("\nClosing connection");
setTextFieldEditable(false);
try {
output.close();
input.close();
client.close();
}
catch (IOException ioException) {
ioException.printStackTrace();
}
}
//envia mensagem ao servidor
private void sendData(String message) {
try //envia o objeto ao servidor
{
output.writeObject("MESA 01 >>" +message);
output.flush();
displayMessage("MESA 01 >>" +message);
}
catch (IOException ioException) {
displayArea.append("\nError writing object");
}
}
//manipula a displayArea na thread de despacho de eventos
private void displayMessage(final String messageToDisplay) {
SwingUtilities.invokeLater(
new Runnable() {
public void run()
{
displayArea.append(messageToDisplay);
}
}
);
}
//manipula o enterField na thread de despacho de eventos
public void setTextFieldEditable(final boolean editable)
{
SwingUtilities.invokeLater(
new Runnable() {
public void run()
{
enterField.setEditable(editable);
}
}
);
}
}
import javax.swing.JFrame;
public class ClientTest {
public static void main (String args[]) {
Client application;
//se não houver nenhum argumento de linha de comando
if (args.length == 0)
application = new Client("127.0.0.1");
else
application = new Client(args[0]);
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.runClient();
}
}
Eu abro o ServerTest e o ClientTest... Roda certinho consigo conversar entre os 2...
Agora eu quero rodar o Client quando eu clicar em um botão...
Como posso fazer isso?