Encerrando Conexão Socket [RESOLVIDO]

2 respostas
M

Boa tarde pessoal, estou com um probleminha hehe

vamos lá,

Tenho uma classe Servidor que cria um ServerSocket e pode receber multiplas conexões.. ela recebe os dados.. envia.. tudo funcionando..
mais quando preciso parar "cortar" a conexão sempre me retorna vaios Exceptions.. vou postar o codigo e quem pudar dar uma olhada e me dizer onde está o erro agradeço,
ja tentei de tudo ou quase e a imaginação está acabando hehe..

A classe cliente não vai receber oque você enviar do servidor... porque não implementei o metodo correto para a leitura de Bytes..
o erro não é esse o erro é quando tento Parar o servidor no botão STOP.
A classe cliente é para simular uma conexão..externa.

ta feio mais funciona ;s

Servidor
import java.awt.Color;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

import javax.swing.text.BadLocationException;
import javax.swing.text.StyleConstants;
import Connection.server.ConnectionFactory;
import ScreenServer.server.TELA_Server;

public class Servidor extends Thread {

	private static ServerSocket servidor = null;
	private static Socket conexao1;
	private static Boolean startup = false;
	private static String Recebida;
	private static String mensagem;
	private static String mensagemreconhecimento;

	public void ConnectionServer() {

		try {

			servidor = new ServerSocket(2222);
			System.out.println("Porta aberta 2222");

			Thread t = new Servidor();
			t.start();
			System.out.println("Entro Thread");

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

	}

	public void run() {

		startup = true;

		try {

			while (startup) {
				System.out.println("Aguardando Conexão..");
				conexao1 = servidor.accept();

				if (startup == true) {
					TELA_Server.getLinhadecomando().setEnabled(true);

					System.out.println("Conectado.");

					StyleConstants.setForeground(TELA_Server.getStyle(),
							Color.GRAY);

					try {

						TELA_Server.getDoc().insertString(
								TELA_Server.getDoc().getLength(),
								"CONNECTED WITH:  "
										+ conexao1.getInetAddress()
												.getHostAddress() + "\n",
								TELA_Server.getStyle());

					} catch (BadLocationException e) {

						e.printStackTrace();

					}

					GetInfo();
					enviaInfCliente();
				} else {
					TELA_Server.getLinhadecomando().setEnabled(false);
				}

			}

		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("Erro ao tentar se conectar !! " + e);
		}

	}

	public void GetInfo() {

		Scanner entrada;

		try {
			entrada = new Scanner(conexao1.getInputStream());

			while (entrada.hasNext()) {

				Recebida = entrada.nextLine();

				System.out.println("RECEBIDO CLIENTE GETINF(): " + Recebida);
				// grava info no banco de dados

				// Split recebida = new Split();
				// new ConnectionFactory();
				// new GravaDAO();
				// GravaDAO.Adiciona(recebida);
				// recebida.setStringRecebida(Recebida);

				// System.out.println("RECEBIDO CLIENTE: " + Recebida);

				StyleConstants
						.setForeground(TELA_Server.getStyle(), Color.BLUE);

				TELA_Server.getDoc().insertString(
						TELA_Server.getDoc().getLength(), Recebida + "\n",
						TELA_Server.getStyle());

			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("ERRO:" + e.getMessage());
		}

	}

	public void enviaInfCliente() {

		OutputStream paraCliente;

		byte[] buffer = new byte[2048];
		// String mensagem;

		try {
			paraCliente = conexao1.getOutputStream();

			mensagem = TELA_Server.getMsgLinhaComando();
			// Mensagens enviadas pela Tela (Server)
			buffer = mensagem.getBytes();
			System.out.println(buffer);
			paraCliente.write(buffer);
			String auxEnviada = new String(buffer);
			System.err.println("Mensagem enviada: " + auxEnviada);

		} catch (Exception e) {
			e.printStackTrace();
			System.out
					.println("Erro ao tentar enviar mesagem" + e.getMessage());
		}

	}

	public static void enviaInfClientDefault() {

		OutputStream paraCliente; // String mensagemreconhecimento;

		byte[] buffer = new byte[2048];

		try {
			paraCliente = conexao1.getOutputStream();
			// paraCliente.flush(); //
			// Mensagem automatica Enviada por Padrão
			mensagemreconhecimento = "Msg:RIID,Dt:01377326,00,End";

			buffer = mensagemreconhecimento.getBytes();
			System.out.println(buffer);
			paraCliente.write(buffer);
			String msgReconecimento = new String(buffer);
			System.err.println("Mensagem enviada: " + msgReconecimento);

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("ERRO:" + e.getMessage());
		}

	}

	

	public void serverCloseConnection() throws IOException {

		try {

			// conexao1.shutdownInput();
			// conexao1.shutdownOutput();
			conexao1.close();
			servidor.close();

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("SERVER DOWN.");
		}

		try {

			StyleConstants.setForeground(TELA_Server.getStyle(),
					Color.LIGHT_GRAY);

			TELA_Server.getDoc().insertString(TELA_Server.getDoc().getLength(),
					"SERVER STOPPED !! \n", TELA_Server.getStyle());
		} catch (BadLocationException e) {
			e.printStackTrace();
		}

	}

	public static String getRecebida() {
		return Recebida;
	}

	public static void setRecebida(String recebida) {
		Recebida = recebida;
	}

	public static Socket getConexao1() {
		return conexao1;
	}

	public static void setConexao1(Socket conexao1) {
		Servidor.conexao1 = conexao1;
	}

	public static ServerSocket getServidor() {
		return servidor;
	}

	public static void setServidor(ServerSocket servidor) {
		Servidor.servidor = servidor;
	}

	public static String getMensagem() {
		return mensagem;
	}

	public static void setMensagem(String mensagem) {
		Servidor.mensagem = mensagem;
	}

TELA

package ScreenServer.server;

import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import javax.swing.JTextField;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

import Server.server.Servidor;

public class TELA_Server extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static JTextField linhadecomando;
	private static JTextField msgLinhaComando;
	private static JLabel txtIMEI;
	private static JLabel txtNOME;
	private static JTextPane telaprincipal;
	private JButton btnIniciar;
	private String nxline = "\n";
	private static StyledDocument doc = null;
	private static Style style = null;
	private Servidor servidor = new Servidor();
	public static TELA_Server singleton;

	public TELA_Server() throws IOException {

		criaTela();

	}

	public void criaTela() {

		setTitle("Teste");
		setResizable(false);
		setSize(650, 500);
		Container cp = getContentPane();
		cp.setLayout(null);
		cp.setVisible(true);

		telaprincipal = new JTextPane();
		doc = telaprincipal.getStyledDocument();

		style = telaprincipal.addStyle("I'am a Style", null);

		doc.addStyle("style", null);

		telaprincipal.setEditable(false);
		JScrollPane src = new JScrollPane(telaprincipal);
		src.setBounds(18, 60, 600, 400);
		cp.add(src);

		btnIniciar = new JButton("START");
		btnIniciar.setBounds(520, 28, 80, 20);
		cp.add(btnIniciar);

		JLabel lblIMEI = new JLabel("ADMIN");
		lblIMEI.setBounds(10, 2, 100, 20);
		cp.add(lblIMEI);

		JLabel lblRowComand = new JLabel("Command line: ");
		lblRowComand.setBounds(2, 29, 120, 20);
		cp.add(lblRowComand);

		linhadecomando = new JTextField();
		linhadecomando.setBounds(110, 26, 400, 25);
		linhadecomando.setEnabled(false);
		cp.add(linhadecomando);

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		btnIniciar.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {

				if (arg0.getSource() == btnIniciar) {
					try {
						if ((btnIniciar.getText().equals("START"))) {

							servidor.ConnectionServer();
							servidor.start();
							btnIniciar.setText("STOP");

							try {
								StyleConstants.setForeground(style,
										Color.LIGHT_GRAY);

								doc.insertString(doc.getLength(),
										"CONNECTING WITH TRACKER...\n", style);
							} catch (Exception e) {
								e.printStackTrace();
							}

						} else {
						
							servidor.serverCloseConnection();
							btnIniciar.setText("START");
							System.out.println("SERVER DOWN !");

						}

					} catch (Exception e) {
						// TODO: handle exception
					}

				}
			}
		});

		linhadecomando.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {

				msgLinhaComando = linhadecomando;

				if (!linhadecomando.getText().equals("")) {
					// if (Ky.getKeyCode() == 10) {

					servidor.enviaInfCliente();

					try {

						StyleConstants.setForeground(style, Color.RED);

						doc.insertString(doc.getLength(), getMsgLinhaComando()
								+ getNxline(), style);
					} catch (BadLocationException e) {
						e.printStackTrace();
					}

					linhadecomando.setText("");

				} else {

					JOptionPane.showMessageDialog(null, "INSERT COMMAND !",
							"Atenção", JOptionPane.WARNING_MESSAGE);

				}
			}
		});

	}

	public static TELA_Server getInstance() throws IOException {
		if (singleton == null) {
			singleton = new TELA_Server();
		}
		return singleton;

	}

	public void StopServer() {
		try {

			servidor.serverCloseConnection();

		} catch (Exception e) {

		}
	}

	// ===========================================================================

	public static void main(String[] args) throws IOException,
			ClassNotFoundException, InstantiationException,
			IllegalAccessException, UnsupportedLookAndFeelException {
		UIManager
				.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");

		/*
		 * SUBSTITUIR CAMPO ACIMA ENTRE () PARÊNTESES PARA MUDAR O VISUAL DA
		 * APLICAÇÃO
		 * 
		 * com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel
		 * javax.swing.plaf.metal.MetalLookAndFeel - Metal
		 * com.sun.java.swing.plaf.windows.WindowsLookAndFeel - Windows
		 * com.sun.java.swing.plaf.motif.MotifLookAndFeel - Motif
		 */
		new TELA_Server().setVisible(true);
		linhadecomando.setEnabled(false);
	}

	public static Style getStyle() {
		return style;
	}

	public static void setStyle(Style style) {
		TELA_Server.style = style;
	}

	public static StyledDocument getDoc() {
		return doc;
	}

	public void setDoc(StyledDocument doc) {
		TELA_Server.doc = doc;
	}

	public static JLabel getTxtNOME() {
		return txtNOME;
	}

	public static void setTxtNOME(JLabel txtNOME) {
		TELA_Server.txtNOME = txtNOME;
	}

	public static JTextField getLinhadecomando() {
		return linhadecomando;
	}

	public static void setLinhadecomando(JTextField linhadecomando) {
		TELA_Server.linhadecomando = linhadecomando;
	}

	public static String getMsgLinhaComando() {
		return msgLinhaComando.getText().trim();
	}

	public void setMsgLinhaComando(JTextField msgLinhaComando) {
		TELA_Server.msgLinhaComando = msgLinhaComando;
	}

	public static JTextPane getTelaprincipal() {
		return telaprincipal;
	}

	public void setTelaprincipal(JTextPane telaprincipal) {
		TELA_Server.telaprincipal = telaprincipal;
	}

	public JButton getBtnIniciar() {
		return btnIniciar;
	}

	public void setBtnIniciar(JButton btnIniciar) {
		this.btnIniciar = btnIniciar;
	}

	public String getNxline() {
		return nxline;
	}

	public void setNxline(String nxline) {
		this.nxline = nxline;
	}

	public static JLabel getTxtIMEI() {
		return txtIMEI;
	}

	public static void setTxtIMEI(JLabel txtIMEI) {
		TELA_Server.txtIMEI = txtIMEI;
	}

}

CLIENTE

import java.io.*;
import java.net.*;

public class ClienteDeChat extends Thread {
	// Flag que indica quando se deve terminar a execução.
	private static boolean done = false;

	public static void main(String args[]) {
		try {
			// Para se conectar a algum servidor, basta se criar um

			// objeto da classe Socket. O primeiro parâmetro é o IP ou
			// o endereço da máquina a qual se quer conectar e o
			// segundo parâmetro é a porta da aplicação. Neste caso,
			// utiliza-se o IP da máquina local (127.0.0.1) e a porta
			// da aplicação ServidorDeChat. Nada impede a mudança
			// desses valores, tentando estabelecer uma conexão com
			// outras portas em outras máquinas.
			Socket conexao = new Socket("127.0.0.1", 2222);

			// uma vez estabelecida a comunicação, deve-se obter os
			// objetos que permitem controlar o fluxo de comunicação
			PrintStream saida = new PrintStream(conexao.getOutputStream());
			// enviar antes de tudo o nome do usuário
			BufferedReader teclado = new BufferedReader(new InputStreamReader(
					System.in));
			System.out.print("Entre com o seu nome: ");
			String meuNome = teclado.readLine();
			saida.println(meuNome);
			// Uma vez que tudo está pronto, antes de iniciar o loop
			// principal, executar a thread de recepção de mensagens.
			Thread t = new ClienteDeChat(conexao);
			t.start();
			// loop principal: obtendo uma linha digitada no teclado e
			// enviando-a para o servidor.
			String linha;
			while (true) {
				// ler a linha digitada no teclado
				System.out.print("> ");
				linha = teclado.readLine();
				// antes de enviar, verifica se a conexão não foi fechada
				if (done) {
					break;
				}
				// envia para o servidor
				saida.println(linha);
			}
		} catch (IOException e) {
			// Caso ocorra alguma excessão de E/S, mostre qual foi.
			System.out.println("IOException: " + e);
		}
	}

	// parte que controla a recepção de mensagens deste cliente
	private Socket conexao;

	// construtor que recebe o socket deste cliente

	public ClienteDeChat(Socket s) {
		conexao = s;
	}

	// execução da thread
	public void run() {
		try {
			BufferedReader entrada = new BufferedReader(new InputStreamReader(
					conexao.getInputStream()));
			String linha;
			while (true) {
				// pega o que o servidor enviou
				linha = entrada.readLine();
				// verifica se é uma linha válida. Pode ser que a conexão
				// foi interrompida. Neste caso, a linha é null. Se isso
				// ocorrer, termina-se a execução saindo com break
				if (linha == null) {
					System.out.println("Conexão encerrada!");
					break;
				}
				// caso a linha não seja nula, deve-se imprimi-la
				System.out.println();
				System.out.println(linha);
				System.out.print("...> ");
			}
		} catch (IOException e) {
			// caso ocorra alguma exceção de E/S, mostre qual foi.
			System.out.println("IOException: " + e);
		}
		// sinaliza para o main que a conexão encerrou.
		done = true;
	}
}

2 Respostas

M

Ninguém ? :frowning:

M

Resolvi Gelera :slight_smile: VLW !

Criado 21 de maio de 2012
Ultima resposta 22 de mai. de 2012
Respostas 2
Participantes 1