Chat dúvida?!

6 respostas
arm.jr

Eu tenho um cliente de chat usando o console para digitar o texto.
Fiz uma interface gráfica mas agora não estou conseguindo pegar os dados da área de texto, enviar para o servidor, ta uma confusão.

Alguem pode me ajudar.

// Cliente

package SODChat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class ClienteDeChat extends Thread {
	private static boolean done = false;

	private Socket conexao;

	public ClienteDeChat(Socket s) { // construtor da classe
		conexao = s;
	}

	public static void main(String args[]) {
		try {

			Socket conexao = new Socket("127.0.0.1", 5151);

			PrintStream saida = new PrintStream(conexao.getOutputStream());

			BufferedReader teclado = new BufferedReader(new InputStreamReader(
					System.in));
			System.out.print("Entre com o seu nome ou Enter para Sair: ");
			String meuNome = teclado.readLine();
			saida.println(meuNome);

			Thread t = new ClienteDeChat(conexao); // cria a thread do cliente
			t.start();

			String linha;
			while (true) {

				System.out.print("&gt ");
				linha = teclado.readLine();

				if (done) {
					break;
				} // testa a condição da variavel para continuar no loop
				saida.println(linha);
			}
		} catch (IOException e) {

			System.out.println("IOException: " + e);
		}
	}

	public void run() {
		try {
			BufferedReader entrada = new BufferedReader(new InputStreamReader(
					conexao.getInputStream()));
			String linha;
			while (true) {

				linha = entrada.readLine();

				if (linha == null) {
					System.out.println("Chat encerrado!");
					break;
				}

				System.out.println();
				System.out.println(linha);
				System.out.print("==&gt ");
			}
		} catch (IOException e) {

			System.out.println("IOException: " + e);
		}

		done = true; // muda o estado da variavel para poder sair do loop
	}
}

6 Respostas

G

Sinceramente eu odeio fazer esse tipo de coisa. Prefico criar o meu chat com interface grafica do 0. Só aproveitando a ideia e algumas linhas do chat ja feito.

Eu ja implemntei um chat tb … só que eo meu éra feito na base do JFrame.
muda um pouco.

mas uma coisa nao muda.

Faça tudo modularizado … por partes … uma coisa é uma coisa e outra coisa é outra coisa. Um de cada vez e nao ponha os bois na frante da carroça. A final como diria jack o bla bla bla bla … por partes.

1º criei uma classe de interface grafica pro servidor.
que tinha:

labels para dizer numero de clientes conectados e esse label tinha seu get e set.

depois eu criei a classe servidor.
esse tinha a funçao iniciar parar.

2º criei a interface do cliente.

Com 2 text area, com seus gets e sets.
1 botao que envia.

depois criei a classe cliente.
q tem a funça mandar e reber


vc ta fazendo com tela de texto … nao muda nada … tenha uma classe que é a interface apenas, e outra que é a classe de funcionalidades.

dai vc pode fazer :

menssagemAEnviar = interfaceGrafica.getMenssagem();

dai nao tem erro, facil leitura e nao se confunde.

Dica: Crie a classe menssagem pois o servidor precisa reconhecer essa classe tambem …

Tenha uma certa organizaçao nos pacotes se nao pode dar pau na hora de executar servidor e clientes em micros separados.

arm.jr

Amigo continuo com dúvida.
Ja ta quase tudo pronto, só falta esse detalhe de pegar da área de texto e enviar para o servidor, eu fiz usando o console e da blz.

No método run() e conectar() que está o pipino.
Já que uso evento do teclado, quando apertar <ENTER> e enviada a mensagem, ta dando erro.

Olha o código logo abaixo.

package SODChat;

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.BevelBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
public class Cliente extends Thread implements ActionListener, KeyListener,
		ChangeListener, Runnable {
	private JTabbedPane tab;
	private JPanel conectar;
	private JSeparator cSepaI;
	private JLabel lPorta;
	private JButton lBConect;
	private JLabel lMeuNome;
	private JSeparator lSeparIII;
	private JSeparator cSeparIV;
	private JLabel cImagemRede;
	private JTextField cTextNomePC;
	private JTextField cMeuIP;
	private JLabel limagem;
	private JTextField lTextIP;
	private JTextField lTextPorta;
	private JTextField lTextNome;
	private JLabel lMeuIP;
	private JLabel lOutrasInfo;
	private JSeparator lSeparII;
	private JLabel lIP;
	private JLabel lNome;
	private JLabel ltitulo;
	private JPanel chat;

	private JFrame frame;

	private Socket conexao;
	private static boolean done = false;

	String meuNome = "";

	public Cliente(){
		
	}
	
	public Cliente(Socket s) throws IOException {
		conexao = s;
		
	}

	private void GUI() {
		try {
			frame = new JFrame("CLIENTE (SODCHAT) v1.0");
			frame.setResizable(false);
			frame.setUndecorated(true);
			frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

			frame.setLayout(null);
			{
				tab = new JTabbedPane();
				frame.getContentPane().add(tab, BorderLayout.CENTER);
				tab.setBounds(0, 0, 440, 450);
				{
					chat = new JPanel();
					{
						conectar = new JPanel();
						tab.addTab("LOGIN", null, conectar, null);

						conectar.setLayout(null);

						conectar.setPreferredSize(new java.awt.Dimension(434,
								378));
						conectar.setBorder(BorderFactory
								.createBevelBorder(BevelBorder.LOWERED));
						{
							ltitulo = new JLabel();
							conectar.add(ltitulo);
							ltitulo.setText("CHAT v1.0");
							ltitulo.setBounds(133, 0, 175, 42);
							ltitulo.setFont(new java.awt.Font("Tahoma", 1, 20));
							ltitulo
									.setForeground(new java.awt.Color(128, 0, 0));
							ltitulo
									.setHorizontalAlignment(SwingConstants.CENTER);
						}
						{
							cSepaI = new JSeparator();
							conectar.add(cSepaI);
							cSepaI.setBounds(0, 42, 434, 7);
							cSepaI.setBorder(new LineBorder(new java.awt.Color(
									0, 0, 0), 1, false));
						}
						{
							lNome = new JLabel();
							conectar.add(lNome);
							lNome.setText("NOME ");
							lNome.setBounds(84, 56, 63, 28);
							lNome.setHorizontalAlignment(SwingConstants.CENTER);
							lNome.setFont(new java.awt.Font("Tahoma", 1, 12));
						}
						{
							lIP = new JLabel();
							conectar.add(lIP);
							lIP.setText("IP DO SERVIDOR");
							lIP.setBounds(56, 119, 112, 28);
							lIP.setHorizontalAlignment(SwingConstants.CENTER);
							lIP.setFont(new java.awt.Font("Tahoma", 1, 12));
						}
						{
							lPorta = new JLabel();
							conectar.add(lPorta);
							lPorta.setText("PORTA");
							lPorta.setBounds(77, 175, 63, 28);
							lPorta.setFont(new java.awt.Font("Tahoma", 1, 12));
							lPorta
									.setHorizontalAlignment(SwingConstants.CENTER);
						}
						{
							lSeparII = new JSeparator();
							conectar.add(lSeparII);
							lSeparII.setBounds(0, 245, 434, 7);
							lSeparII.setBorder(new LineBorder(
									new java.awt.Color(0, 0, 0), 1, false));
						}
						{
							lOutrasInfo = new JLabel();
							conectar.add(lOutrasInfo);
							lOutrasInfo.setText("OUTRAS INFORMAÇÕES");
							lOutrasInfo.setBounds(7, 259, 266, 28);
							lOutrasInfo.setFont(new java.awt.Font("Tahoma", 1,
									20));
							lOutrasInfo.setForeground(new java.awt.Color(64, 0,
									0));
							lOutrasInfo
									.setHorizontalAlignment(SwingConstants.CENTER);
						}
						{
							lBConect = new JButton();
							conectar.add(lBConect);
							lBConect.setText("Conectar...");
							lBConect.setBounds(252, 217, 175, 21);
							lBConect
									.setFont(new java.awt.Font("Tahoma", 1, 12));
							lBConect.addActionListener(this);
						}
						{
							lMeuIP = new JLabel();
							conectar.add(lMeuIP);
							lMeuIP.setText("MEU IP");
							lMeuIP.setBounds(21, 312, 63, 28);
							lMeuIP.setHorizontalAlignment(SwingConstants.LEFT);
							lMeuIP.setFont(new java.awt.Font("Tahoma", 1, 12));
						}
						{
							lMeuNome = new JLabel();
							conectar.add(lMeuNome);
							lMeuNome.setText("NOME DO PC");
							lMeuNome.setBounds(21, 369, 91, 28);
							lMeuNome
									.setHorizontalAlignment(SwingConstants.LEFT);
							lMeuNome
									.setFont(new java.awt.Font("Tahoma", 1, 12));
						}
						{
							lTextNome = new JTextField();
							conectar.add(lTextNome);
							lTextNome.setBounds(35, 91, 154, 21);
							lTextNome
									.setHorizontalAlignment(SwingConstants.CENTER);
							lTextNome
									.setFont(new java.awt.Font("Tahoma", 0, 12));
							lTextNome
									.setForeground(new java.awt.Color(0, 0, 64));

						}
						{
							lTextPorta = new JTextField();
							conectar.add(lTextPorta);
							lTextPorta.setBounds(35, 210, 154, 21);
							lTextPorta
									.setHorizontalAlignment(SwingConstants.CENTER);
							lTextPorta.setFont(new java.awt.Font("Tahoma", 0,
									12));
							lTextPorta.setForeground(new java.awt.Color(0, 0,
									64));
							lTextPorta.setText("5151");
							lTextPorta.setEditable(false);
						}
						{
							lTextIP = new JTextField();
							conectar.add(lTextIP);
							lTextIP.setBounds(35, 154, 154, 21);
							lTextIP
									.setHorizontalAlignment(SwingConstants.CENTER);
							lTextIP.setFont(new java.awt.Font("Tahoma", 0, 12));
							lTextIP.setForeground(new java.awt.Color(0, 0, 64));
						}
						{
							limagem = new JLabel();
							limagem.setIcon(new ImageIcon(getClass()
									.getResource("messenger.jpg")));
							conectar.add(limagem);
							limagem.setBounds(252, 56, 175, 154);
						}
						{
							lSeparIII = new JSeparator();
							conectar.add(lSeparIII);
							lSeparIII.setBounds(245, 49, 7, 196);
							lSeparIII.setOrientation(SwingConstants.VERTICAL);
						}
						{
							cMeuIP = new JTextField();
							conectar.add(cMeuIP);
							cMeuIP.setBounds(119, 315, 147, 21);
							cMeuIP
									.setHorizontalAlignment(SwingConstants.CENTER);
							cMeuIP.setFont(new java.awt.Font("Tahoma", 1, 12));
							cMeuIP.setForeground(new java.awt.Color(128, 0, 0));
							cMeuIP.setEditable(false);
							cMeuIP.setText(InetAddress.getLocalHost()
									.getHostAddress());
						}
						{
							cTextNomePC = new JTextField();
							conectar.add(cTextNomePC);
							cTextNomePC.setBounds(119, 371, 147, 21);
							cTextNomePC
									.setHorizontalAlignment(SwingConstants.CENTER);
							cTextNomePC.setFont(new java.awt.Font("Tahoma", 1,
									12));
							cTextNomePC.setForeground(new java.awt.Color(128,
									0, 0));
							cTextNomePC.setEditable(false);
							cTextNomePC.setText(InetAddress.getLocalHost()
									.getHostName());
						}
						{
							cImagemRede = new JLabel();
							conectar.add(cImagemRede);
							cImagemRede.setBounds(301, 259, 126, 154);
							cImagemRede.setIcon(new ImageIcon(getClass()
									.getResource("redePC.jpg")));
							cImagemRede
									.setHorizontalAlignment(SwingConstants.CENTER);
						}
						{
							cSeparIV = new JSeparator();
							conectar.add(cSeparIV);
							cSeparIV.setBounds(294, 252, 7, 168);
							cSeparIV.setOrientation(SwingConstants.VERTICAL);
						}
					}
				}
			}
			tab.addTab("CLIENTE", null, panCliente(lTextIP.getText()), null);
			frame.pack();
			frame.setSize(449, 485);
			centralizar(frame);
			frame.setVisible(true);
			tab.setEnabledAt(1, false);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Variáveis da interface gráfica ( CLIENTE ).
	 */

	private JTextArea entrada;

	private JTextArea mensagens;

	private JLabel LTitulo;

	private JScrollPane scrollPaneI;

	private JScrollPane scrollPaneII;

	private JButton BcorFonte;

	private JButton BcorPainel;

	private JButton Blimpar;

	private JSeparator separ;

	private JToggleButton bTop;

	public JPanel panCliente(String ip) {

		chat = new JPanel();
		chat.setLayout(null);
		chat.setPreferredSize(new java.awt.Dimension(434, 399));
		chat.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));

		scrollPaneI = new JScrollPane(mensagens);
		chat.add(scrollPaneI);
		scrollPaneI.setBounds(14, 42, 413, 273);
		mensagens = new JTextArea();
		mensagens.setLineWrap(true);
		mensagens.setEditable(false);
		scrollPaneI.setViewportView(mensagens);
		LTitulo = new JLabel();
		chat.add(LTitulo);
		LTitulo.setBounds(14, 6, 413, 26);
		LTitulo.setFont(new java.awt.Font("Verdana", 1, 18));
		LTitulo.setForeground(new java.awt.Color(0, 0, 160));
		LTitulo
				.setBorder(BorderFactory
						.createEtchedBorder(BevelBorder.LOWERED));
		LTitulo.setHorizontalAlignment(SwingConstants.CENTER);
		BcorPainel = new JButton();
		chat.add(BcorPainel);
		BcorPainel.setText("COR FUNDO");
		BcorPainel.setBounds(14, 325, 133, 21);
		BcorPainel.setBackground(new java.awt.Color(223, 221, 189));
		BcorPainel.addActionListener(this);

		BcorFonte = new JButton();
		chat.add(BcorFonte);
		BcorFonte.setText("FONTE");
		BcorFonte.setBounds(161, 325, 77, 21);
		BcorFonte.setBackground(new java.awt.Color(223, 221, 189));
		BcorFonte.addActionListener(this);

		Blimpar = new JButton();
		chat.add(Blimpar);
		Blimpar.setText("LIMPAR");
		Blimpar.setBounds(329, 325, 98, 21);
		Blimpar.setBackground(new java.awt.Color(214, 217, 187));
		Blimpar.addActionListener(this);

		bTop = new JToggleButton();
		chat.add(bTop);
		bTop.setText("TOPO");
		bTop.setBounds(252, 325, 70, 21);
		bTop.setBackground(new java.awt.Color(223, 221, 189));
		bTop.addActionListener(this);

		separ = new JSeparator();
		chat.add(separ);
		separ.setBounds(14, 350, 413, 7);
		separ.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
		scrollPaneII = new JScrollPane();
		chat.add(scrollPaneII);
		scrollPaneII.setBounds(14, 364, 413, 49);
		scrollPaneII.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
		entrada = new JTextArea(); // create entrada
		scrollPaneII.setViewportView(entrada);

		// entrada.setEditable(false);

		entrada.setBackground(new java.awt.Color(255, 255, 255));
		entrada.setFont(new java.awt.Font("Tahoma", 1, 14));
		entrada.setLineWrap(true);
		entrada.addKeyListener(this);
		return chat;

	}

	/**
	 * AÇÕES, QUANDO O USUÁRIO CLICAR NOS BOTÕES.
	 */
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == lBConect) {
			LTitulo.setText(lTextNome.getText().equals("") ? "CLIENTE"
					: lTextNome.getText());
			tab.setSelectedIndex(1);
			tab.setEnabledAt(1, true);
			tab.setEnabledAt(0, false);
			SwingWorker worker = new SwingWorker() {
				public Object construct() {
					try {
						conectar();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					return "a";
				}
			};
			worker.start();
		}
		// botão TOPO
		if (e.getSource() == bTop) {
			if (bTop.isSelected())
				frame.setAlwaysOnTop(true);
			else
				frame.setAlwaysOnTop(false);
		}
		// Botão LIMPAR
		if (e.getSource() == Blimpar) {
			entrada.setText("");
			mensagens.setText("");
		}
		// Botão COR PAINEL
		if (e.getSource() == BcorPainel) {
			CorFonteFundo(false);
		}
		// Botão COR FONTE
		if (e.getSource() == BcorFonte) {
			CorFonteFundo(true);
		}

		// ALTERAÇÃO DE CORES, FONTE e PAINEL
		if (e.getSource() == comboFontes) {
			LTitulo.setFont(new Font((String) comboFontes.getSelectedItem(),
					(int) comboEstilo.getSelectedIndex(), 18));
			entrada.setFont(new Font((String) comboFontes.getSelectedItem(),
					(int) comboEstilo.getSelectedIndex(),
					TamFonte((String) comboTamanho.getSelectedItem())));
			mensagens.setFont(new Font((String) comboFontes.getSelectedItem(),
					(int) comboEstilo.getSelectedIndex(),
					TamFonte((String) comboTamanho.getSelectedItem())));
		}
		if (e.getSource() == comboTamanho) {
			LTitulo.setFont(new Font((String) comboFontes.getSelectedItem(),
					(int) comboEstilo.getSelectedIndex(), 18));
			entrada.setFont(new Font((String) comboFontes.getSelectedItem(),
					(int) comboEstilo.getSelectedIndex(),
					TamFonte((String) comboTamanho.getSelectedItem())));
			mensagens.setFont(new Font((String) comboFontes.getSelectedItem(),
					(int) comboEstilo.getSelectedIndex(),
					TamFonte((String) comboTamanho.getSelectedItem())));
		}
		if (e.getSource() == comboEstilo) {
			LTitulo.setFont(new Font((String) comboFontes.getSelectedItem(),
					(int) comboEstilo.getSelectedIndex(), 18));
			entrada.setFont(new Font((String) comboFontes.getSelectedItem(),
					(int) comboEstilo.getSelectedIndex(),
					TamFonte((String) comboTamanho.getSelectedItem())));
			mensagens.setFont(new Font((String) comboFontes.getSelectedItem(),
					(int) comboEstilo.getSelectedIndex(),
					TamFonte((String) comboTamanho.getSelectedItem())));
		}

	}

	/**
	 * EVENTOS DO TECLADO, na área de texto ao clicar &lt;ENTER&gt; a mensagem será
	 * enviada.
	 */
	public void keyPressed(KeyEvent e) {
		switch (e.getKeyCode()) {
		case Event.ENTER:
			if (entrada.getText().length() != 0) {

				try {
					try {
						enviaMensagem(entrada.getText());
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					entrada.setText(&quot;&quot;);
					pressionaBackSpace(); // retorna a 1º linha da área de
					// texto.
				} catch (AWTException e1) {
					e1.printStackTrace();
				}
			}
			break;
		}

	}

	public void keyReleased(KeyEvent e) {
	}

	public void keyTyped(KeyEvent e) {
	}

	/*
	 * xxxxxxxxxxxxxxxxxxxxx METODOS PARA ALTERAÇÃO DA COR, FONTE DA INTERFACE
	 * GRÁFICA xxxxxxxxxxxxxxxxxxxxxxxxx
	 */

	protected void pressionaBackSpace() throws AWTException {
		Robot rbt = new Robot();
		rbt.keyPress(KeyEvent.VK_BACK_SPACE);
		rbt.keyRelease(KeyEvent.VK_BACK_SPACE);
	}

	/**
	 * Centraliza o FRAME na tela.
	 */
	protected static void centralizar(JFrame frame) {
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension windowSize = frame.getSize();
		int x = (int) ((screenSize.getWidth() - windowSize.getWidth()) / 2);
		int y = (int) ((screenSize.getHeight() - windowSize.getHeight()) / 2);

		frame.setLocation(x, y);
	}

	/**
	 * Retorna o tamanho da FONTE
	 * 
	 * @param ob -&gt
	 *            valor da comboTamanho
	 * @return
	 */
	private int TamFonte(String ob) {
		return Integer.parseInt(ob);
	}

	/**
	 * Variáveis para a alteração da cor e fonte da interface gráfica.
	 */
	private JColorChooser tcc;

	private boolean controlTipo;

	private JComboBox comboFontes;

	private JComboBox comboTamanho;

	private JComboBox comboEstilo;

	/**
	 * Método responsável pela alteração de cores da fonte e painel da GUI.
	 * 
	 * @param tipo -
	 *            TRUE &gt altera o tipo de fonte e cor, FALSE -&gt altera a cor do
	 *            painel.
	 */
	public void CorFonteFundo(boolean tipo) {
		controlTipo = tipo;
		JDialog.setDefaultLookAndFeelDecorated(true);
		JDialog frameCor = new JDialog();
		frameCor.setTitle(&quot;Alterar Cores ( CLIENTE )&quot;);
		frameCor.setDefaultCloseOperation(frameCor.DISPOSE_ON_CLOSE);
		frameCor.setResizable(false);
		frameCor.setAlwaysOnTop(true);

		tcc = new JColorChooser();

		JPanel pan = new JPanel(new BorderLayout());

		Container norte = new Container();
		norte.setSize(200, 100);
		norte.setLayout(new GridLayout(3, 2));
		if (tipo) {
			JLabel LFontes = new JLabel(&quot;FONTES&quot;);
			LFontes.setFont(new Font(&quot;Arial&quot;, Font.PLAIN, 14));

			JLabel LTamanho = new JLabel(&quot;TAMANHO&quot;);
			LTamanho.setFont(new Font(&quot;Arial&quot;, Font.PLAIN, 14));

			JLabel LEstilo = new JLabel(&quot;ESTILO&quot;);
			LEstilo.setFont(new Font(&quot;Arial&quot;, Font.PLAIN, 14));

			comboFontes = new JComboBox(Listarfontes().toArray());
			comboFontes.addActionListener(this);

			comboTamanho = new JComboBox(new String[] { &quot;12&quot;, &quot;14&quot;, &quot;16&quot;, &quot;18&quot;,
					&quot;20&quot;, &quot;25&quot;, &quot;30&quot;, &quot;35&quot;, &quot;40&quot; });
			comboTamanho.addActionListener(this);

			comboEstilo = new JComboBox(new String[] { &quot;Normal&quot;, &quot;Negrito&quot;,
					&quot;Itálico&quot; });
			comboEstilo.addActionListener(this);

			norte.add(LFontes);
			norte.add(comboFontes);
			norte.add(LTamanho);
			norte.add(comboTamanho);
			norte.add(LEstilo);
			norte.add(comboEstilo);
			tcc.setBorder(BorderFactory.createTitledBorder(&quot;Cores da Fonte&quot;));
			frameCor.setLocation(370, 150);
		} else {
			tcc.setBorder(BorderFactory.createTitledBorder(&quot;Cor do Painel&quot;));
			frameCor.setLocation(370, 200);
		}

		tcc.getSelectionModel().addChangeListener(this);

		pan.setOpaque(true);
		pan.add(norte, BorderLayout.NORTH);
		pan.add(tcc, BorderLayout.CENTER);

		frameCor.getContentPane().add(pan, BorderLayout.NORTH);
		frameCor.pack();
		frameCor.setVisible(true);
	}

	/**
	 * Lista todas as fontes que existe no PC.
	 * 
	 * @return - Vector com as fontes para adicionar na comboFontes
	 */
	private Vector&lt;String&gt; Listarfontes() {
		Vector&lt;String&gt; result = new Vector&lt;String&gt;();

		GraphicsEnvironment env = GraphicsEnvironment
				.getLocalGraphicsEnvironment();
		Font[] fonts = env.getAllFonts();
		for (int i = 1; i &lt fonts.length; i++)
			result.add(fonts[i].getFontName());
		return result;
	}

	/**
	 * EVENTO PARA ALTERAR AS CORES DOS COMPONENTES.
	 */
	public void stateChanged(ChangeEvent e) {
		Color newColor = tcc.getColor();
		if (controlTipo) {
			entrada.setForeground(newColor);
			mensagens.setForeground(newColor);
			LTitulo.setForeground(newColor);
		} else {
			chat.setBackground(newColor);
		}

	}

	private PrintStream saida;

	public void conectar() throws ClassNotFoundException {
		try {

			Socket conexao = new Socket(&quot;127.0.0.1&quot;, 5151);

			saida = new PrintStream(conexao.getOutputStream());

			BufferedReader teclado = new BufferedReader(new InputStreamReader(
					System.in));
			
			System.out.print(&quot;Entre com o seu nome ou Enter para Sair: &quot;);
			
			String meuNome = lTextNome.getText();
			
			saida.println(meuNome);

			Thread t = new Cliente(conexao); // cria a thread do cliente
			t.start();

			String linha;
			
			while (true) {
				System.out.print(&quot;&gt &quot;);
				linha = teclado.readLine();
				saida.println(linha);
			}
		} catch (IOException e) {

			System.out.println(&quot;IOException: &quot; + e);
		}
	}

	private void enviaMensagem(String message) throws IOException {
		SimpleDateFormat form = new SimpleDateFormat(&quot;k:mm&quot;);
		saida.println(&quot;\n&quot; + meuNome.toUpperCase() + &quot; [&quot;
				+ form.format(new Date()) + &quot;] &gt&gt &quot; + message);
		saida.flush();
		entradaMensagem(&quot;\n&quot; + meuNome.toUpperCase() + &quot; [&quot;
				+ form.format(new Date()) + &quot;] &gt&gt &quot; + message);
	}

	/**
	 * Esse método envia para a área de texto do CLIENTE as mensagens digitadas
	 * por ele.
	 * 
	 * @param mensagem -&gt
	 *            mensagens.
	 */
	private void entradaMensagem(final String mensagem) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				mensagens.append(mensagem);
			}
		});
	}

	

	public void run() {
		try {
			BufferedReader entrada = new BufferedReader(new InputStreamReader(
					conexao.getInputStream()));
			String linha;
			
			while (true) {
//				linha = entrada.readLine();
//				if (linha == null) {
//					System.out.println(&quot;Chat encerrado!&quot;);
//					break;
//				}
			}
		} catch (IOException e) {

			System.out.println(&quot;IOException: &quot; + e);
		}

//		done = true; // muda o estado da variavel para poder sair do loop
	}

	public static void main(String[] args) throws IOException {
		new Cliente().GUI();

	}

}
lina

Oi,
seu objeto de comunicação deve ter algum método send para enviar as mensagens né?
ou uma variavel que tenha o conteudo send.

Receba o seu texto que esta no textarea de entrada... depois passe o que recebeu para o outro usuario da outra linha.... com o código abaixo:

io_sk = variavel de envio.... (possui o método send)

byte[]
lh_buffer = io_ta_texto_envia.getText().getBytes();

//
// Se estiver connectado ....
//
if (conexao.isConnected())
{						
	try
	{
		//
		// Manda a String.
		//
		io_ta_texto_vista.setText(io_ta_texto_vista.getText()+"\nLina diz: "+"\r\n"+new String(lh_buffer)+"\n");	
		//
		// Envia o buffer ...
		//
		conexao.io_sk.SendAll(lh_buffer);
	}
	catch (VeSCommNotConnectedException ex)
	{
		//
		// Exceção.
		//					
	}
}

Tchauzin!

arm.jr

Mas tem que colocar isso dentro do método run() da thread?

lina

Assim,
você deve ter 2 Thread para envio e recebimento… ou seja método Send deve extender a uma Thread e receive tbm…
um objeto de comunicação e outro para conexão…

analizei ali e seu conexão se chama (conexao)…

esse objeto de comunicação deve ter os métodos, Send, Receive, Connect, Disconnect… etc…

esse código que eu postei acima, deve ficar no Run do teu Send.

Ta meiu confuso…

lina

Olha só,
tem um tutorial aqui no guj, que mostra a utilização de sockets… para um client e um servidor…
não sei se você já deu uma olhada… mais link ta ai:

http://www.guj.com.br/java.tutorial.artigo.126.1.guj

Criado 20 de março de 2007
Ultima resposta 20 de mar. de 2007
Respostas 6
Participantes 3