如何向我的服务器添加线程? [英] How do I add thread to my server?

查看:111
本文介绍了如何向我的服务器添加线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的初学者,我已完成构建P2p文件共享Java应用程序的任务. 我首先创建服务器和客户端.客户端可以向服务器发送消息,并且服务器可以响应.我相信下一步应该是将Thread插入服务器类.我阅读了所有相关内容,并尝试将其发芽,但我无法将其关闭.我希望有一个人可以帮助我. 这是服务器类:

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);
       }    
    } 
  }
}

这是客户端类:

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);
    }
  }
 }
}

解决方案

这是一种非常简单的方法-我没有阅读所有代码,因此请进行测试以确保它不会破坏任何内容.

>

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
}

基本上,您每次都在新线程中执行处理程序.看来处理程序不需要将数据返回到主循环,所以应该没事.

否则您可能会有太多线程,因此实际上您应该查看Executors.newFixedThreadPool()(

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);
    }
  }
 }
}

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.

这篇关于如何向我的服务器添加线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆