开发者

How do I add thread to my server?

开发者 https://www.devze.com 2022-12-15 00:01 出处:网络
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

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.equ开发者_运维技巧als("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);
    }
  }
 }
}


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"


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消