kłopot z działaniem sieci (klient - serwer)

0

Witam Serdecznie,
Probuje stworzyć małą sięc składającą się z serwera i kilku klientów. Niestety podczas kompilacji następują następujące problemy:

1.Podczas próby stworzenia klienta do konsoli wypisywany jest komunikat:
"Poczatek try
IO exception while connecting to the server.
Zwiększam numer portu o 1
Obecny numer portu to :20013
Poczatek try" i tak w kółko - nie moze utworzyć socketu dla klienta

2.Jak jeszcze tworzenie klienta działało w miare poprawnie do serwera dochodziły wiadomości, serwer odpowiadał ale klient nie potrafił jej odebrać, ponieważ nie wypisywał do konsoli tego co do niego przyszło. Jak moge zaaranżować poprawnie strukturowo wymianę informacji tekstowych? Nie musi być ładnie byleby sprawnie działało.

kod:

Serwer:

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;

public class Server implements Runnable
{

	private ServerSocket serverSocket;

	private Vector<ServerService> clients = new Vector<ServerService>();

	private int port = 20001;

	private boolean z = true;


	public Server() 
	{

		while(z && port < 20500)
		{
			try 
			{
				serverSocket = new ServerSocket(port);
				System.out.println("socket utworzony");
				z = false;
			} 
			catch (IOException e) 
			{
				System.err.println("Error starting Server.");
				z = true;
				port++;
				//System.exit(1);
			}
		}
	}

	public void run() 
	{
		while (true)
			try 
		{
				Socket clientSocket = serverSocket.accept();
				ServerService clientService = new ServerService(clientSocket, this);
				addClientService(clientService);
		} 
		catch (IOException e) 
		{
			System.err.println("Error accepting connection");
		}
	}

	synchronized void addClientService(ServerService clientService)throws IOException 
	{
		clientService.init();
		clients.addElement(clientService);
		new Thread(clientService).start();
		System.out.println("Add. " + clients.size());
	}


	synchronized void removeClientService(ServerService clientService) 
	{
		clients.removeElement(clientService);
		clientService.close();
		System.out.println("Remove. " + clients.size());
	}


	public static void main(String args[]) 
	{
		ServerConfig.initialize();
		Server s = new Server();
		s.run();

	}

}

obsługa serwera:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.Socket;
import java.util.StringTokenizer;



public class ServerService implements Runnable 
{
	
	private int id;
	@SuppressWarnings("unused")
	private Server server;
	private Socket clientSocket;
	private BufferedReader input;
    private PrintWriter output;

    public ServerService(Socket clientSocket, Server server) 
	{
    	this.server = server;
	    this.clientSocket = clientSocket;
	}

	void init() throws IOException 
	{
		Reader reader = new InputStreamReader(clientSocket.getInputStream());
	    input = new BufferedReader(reader);
	    output = new PrintWriter(clientSocket.getOutputStream(), true);
	}

	void close() 
	{
		try 
		{
			output.close();
			input.close();
			clientSocket.close();
		} 
		catch (IOException e) 
		{
			System.err.println("Error closing client (" + id + ").");
		} 
		finally 
		{
			output = null;
			input = null;
			clientSocket = null;
		}
	}

	public void run() 
	{
		while (true) 
		{
			String request = receive();
			StringTokenizer st = new StringTokenizer(request);
			String message = st.nextToken();
			ServerRequestResponse.RequestResponse(message);

		}
	}

	void send(String command) 
	{
		output.println(command);
	}

	private String receive() 
	{
		try 
		{
			return input.readLine();
		} 
		catch (IOException e) 
		{
			System.err.println("Error reading client (" + id + ").");
		}
		return ServerProtocol.NULL_MESSAGE;
	}
}

Klient:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.StringTokenizer;


public class Klient implements Runnable 
{

	static final String A = "a";
	
	static final String AnswerA = "odpowiedz na a";
	
	static final String B = "b";
	
	static final String AnswerB = "odpowiedz na b";
	
	private Socket socket = null;

	private BufferedReader input;

	private PrintWriter output;

	private int port = 20010;

	public Klient() throws Exception 
	{
		while(true)
		{
			try 
			{
				System.out.println("Poczatek try");
				socket = new Socket("localhost", port); // TUTAJ RZUCA WYJĄTKIEM, DLACZEGO?
				System.out.println("Po utworzeniu socket");
				break;

			}
			catch (UnknownHostException e) 
			{
				System.err.println("Unknown host.");
			}
			catch (IOException e) 
			{	
				System.err.println("IO exception while connecting to the server.");
				System.out.println("Zwiększam numer portu o 1");
				++port;
				System.out.println("Obecny numer portu to :" + port);
			} 
			catch (NumberFormatException e) 
			{
				System.err.println("Port value must be a number.");
			}
		}
		
		try 
		{
			input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			output = new PrintWriter(socket.getOutputStream(), true);
		} 
		catch (IOException ex) 
		{
			throw new Exception("Can not get input/output connection stream.");
		}
		
		new Thread(this).start();
		send(A);
	}

	synchronized boolean isDisconnected() 
	{
		return socket == null;
	}

	public void run() 
	{
		while (true)
			try 
		{
				String command = input.readLine();
				if (!handleCommand(command)) 
				{
					output.close();
					input.close();
					socket.close();
					break;
				}
		} catch (IOException e) 
		{
		}
		output = null;
		input = null;
		synchronized (this) 
		{
			socket = null;
		}
	}

	private boolean handleCommand(String command) 
	{
		StringTokenizer st = new StringTokenizer(command);
		String cd = st.nextToken();
		if (cd.equals(AnswerA)) 
		{
			st.nextToken();// id
			System.out.println("Dostałem odpowiedź a");
		}

		return true;
	}


	void send(String command) 
	{
		if (output != null)
			output.println(command);
	}


	public static void main(String args[]) throws Exception 
	{

		Klient k = new Klient();
		k.run();

	}

}
0

Masz bezsensowną obsługę wyjątku. Zmień na:

            catch (IOException e) 
            {
                //System.err.println("Error starting Server.");
                System.err.println(e);
                z = true;
                port++;
                //System.exit(1);
            }

1 użytkowników online, w tym zalogowanych: 0, gości: 1