Soket basico

2 respostas
A

Boa tarde,
estou tentando fazer este codigo rodar so que nao consigo identificar o que causa o erro. Muito Obrigado!

public class Servidor {
		String[] lista = {"Alexandre","Reis"}; 
	
	    public void go2(){
	    	try {
				
	    		ServerSocket server = new ServerSocket(4000);
	    		
	    		while(true){
	    			Socket soket = server.accept();
	    			
	    			PrintWriter writer = new PrintWriter(soket.getOutputStream());
	    			String advice = listaDeNomes();
	    			writer.println(advice);
	    			writer.close();
	    			System.out.println(advice);
	    		}
	    		
	    		
			} catch (IOException e) {
				e.printStackTrace();
			}
	    	
	    }
		
	    private String listaDeNomes(){
	    	int random = (int) (Math.random() * lista.length);
	    	return lista [random];
	    }
		
	public static void main(String[] args) {
			Servidor ser = new Servidor();
			ser.go2();

	}

}
public class CaixaDeTexto {
	
	JTextField textoEnviar;
	PrintWriter escrever;
	Socket sok;
	
	public void go(){
		JFrame frame = new JFrame("Frame aki");
		JPanel painel = new JPanel();
		JTextField texto= new JTextField(20);
		JButton botao = new JButton("Enviar");
		
		botao.addActionListener(new BotaoEnviarTexto());
		painel.add(texto);
		painel.add(botao);
		frame.getContentPane().add(BorderLayout.CENTER, painel);
		
		conexaoSoket();
		frame.setSize(400,500);
		frame.setVisible(true);
	}
	
	private void conexaoSoket(){
		try {
			sok = new Socket("189.123.25.51", 4000);
			escrever = new PrintWriter(sok.getOutputStream());
			System.out.println("Conexao estabelicida!"); 
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public class BotaoEnviarTexto implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			try {
				escrever.println(textoEnviar.getText());
				escrever.flush();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			textoEnviar.setText("");
			textoEnviar.requestFocus();
		}
		
		
	}
	
	public static void main(String[] args) {
		CaixaDeTexto caixa = new CaixaDeTexto();
		caixa.go();
	}

}

2 Respostas

M

Você não instanciou o seu JTextField textoEnviar.

M

Outra coisa: não adianta escrever no socket se você não lê os dados que chegou do outro lado. Falta um Scanner em algum lugar (no cliente, no servidor ou em ambos).

Criado 9 de fevereiro de 2010
Ultima resposta 9 de fev. de 2010
Respostas 2
Participantes 2