views:

83

answers:

2

I'm a beginner in Java and I have an assignment to build P2p File Sharing Java application. I started by creating server and client. Client can send messages to server and server responds. I believe the next step should be inserting the Thread into the server class. I read all about it and tried it bud I just can't pull it off. I hope someone can help me. Here is server class:

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

public class Server {

  private static ServerSocket serverskiSoket;
  private final static int PORT = 3334;

  public static void main(String[] args) {
    System.out.println("Server se povezuje na port: "+PORT);

    try {
        serverskiSoket = new ServerSocket(PORT);
        System.out.println("Server aktivan: " + serverskiSoket);
        System.out.println("Ceka se klijent ...");
    } catch (IOException ex) {
        String dodatnaPoruka = ex.getMessage().toString();

        if (dodatnaPoruka.equals("Address already in use: JVM_Bind"))
            System.out.println("Nemoguce je povezati se na port "+ PORT +" jer je zauzet od strane drugog servera.");
            System.exit(1);
    }

    do { 
        handleClient();
    } while(true);
  }

  private static void handleClient() {
    Socket link = null;

    try {
        link = serverskiSoket.accept();
        System.out.println("Klijent povezan: " + link);

        Scanner ulazniTok = new Scanner(link.getInputStream());
        PrintWriter izlazniTok = new PrintWriter(link.getOutputStream(), true);

        int brojPoruka = 0;
        String poruka = ulazniTok.nextLine();

        while(!poruka.equals("zatvori")) {
          System.out.println("Klijent kaze: " + poruka);
          brojPoruka++;
          izlazniTok.println("Poruka: " + brojPoruka + ": " + poruka);
          poruka = ulazniTok.nextLine();
        }

        izlazniTok.println(brojPoruka + " poruka poslato.");
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
       try {
           System.out.println("Konekcija se zatvara...");
           link.close();
       } catch(IOException ioEx) {
           System.out.println("Diskonekcija nije moguca! \nRazlog: " + ioEx.getMessage());
           System.exit(1);
       }    
    } 
  }
}

and here is Client class:

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

public class Klijent {

  private static InetAddress host;
  private static final int PORT = 3334;

  public static void main(String[] args) {
    System.out.println("Povezivanje klijenta u toku. Molim sacekajte...");

    try {
        host = InetAddress.getLocalHost();
    } catch (UnknownHostException ex) {
        System.out.println("ID hosta nije pronadjen");
        System.exit(1);
    }

    pristupiServeru();
  }

  private static void pristupiServeru() {
    Socket link = null;

    try {
      link = new Socket(host, PORT);
      String IPAdresa = StringCutter.RaseciString(host.toString());
      System.out.println("Povezan na host cija je IP adresa: "+IPAdresa+", a port: "+PORT);


      Scanner ulazniTok = new Scanner(link.getInputStream());
      PrintWriter izlazniTok = new PrintWriter(link.getOutputStream(), true);

      Scanner unosKorisnika = new Scanner(System.in);

      String poruka, odgovor;

      do {
        System.out.println("Unesite poruku: ");
        poruka = unosKorisnika.nextLine();
        izlazniTok.println(poruka);
        odgovor = ulazniTok.nextLine();
        if (!odgovor.contains("primljeno"))
          System.out.println("Rekli ste serveru: " + odgovor);
        else System.out.println(odgovor);
    } while (!poruka.equals("zatvori"));
  } catch (IOException ex) {
     ex.printStackTrace();
  } finally {
    try {
        System.out.println("\n*Zatvara se konekcija sa serverom...*");
        link.close();
    } catch (IOException ex){
        System.out.println("Diskonekcija je nemoguca");
        System.exit(1);
    }
  }
 }
}
+1  A: 

Here's a really simple way of doing it - I didn't read through all that code so test this to make sure it doesn't break anything.

private static void handleClient() {
  new Thread() {
    public void run() {
      Socket link = null;
      ...
        } catch(IOException ioEx) {
           System.out.println("Diskonekcija nije moguca! \nRazlog: " + ioEx.getMessage());
           System.exit(1);
       }    
    } // end outer try
  }.start() // end thread
}

Basically, you are executing the handler in a new thread each time. It looks like the handler doesn't ever need to return data to the main loop so that should be fine.

Except then you might have too many threads, so really you should look at Executors.newFixedThreadPool() (http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool%28int%29) for pooling.

Edit: skimming the code, one problem I can see is that your outputs might be interleaved among threads. Not sure if you care about that - I can't read whatever language the output is in.

danben
Fixed.Thank you again :)Yes, I'm new around here and I hope I'll get around fine.
SlavishaZero
+1  A: 

Have you looked at the Java socket tutorials? They give an example of a multi threaded server on one of the pages. Try to mimic what they are doing in their code (you will need to make another class). You can find the sample code at the bottom of this page: http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html

Look for the heading "Supporting Multiple Clients"

Roman Stolper
Thank you danben, I planted your code into the server and it works just fine. There was another exception I had to take care of, but otherwise it is great.I'm sorry I didn't translate from Serbian into English, I realized just now I made that mistake.@Roman StolperYeah I've seen that page. It is one of many so I didn't think it was important and useful. Now that you've told me I'll surely go and read it through. Thanks again
SlavishaZero
You're welcome. Glad it worked out - it'd be great if you could mark my answer as accepted.
danben
Also, since you're new here - generally if you wanted to respond to me you'd leave the comment on my answer. No biggie though, I found it.
danben