創建一個允許通過線程和Java進行多重連接的套接字服務器java


Answers


你不是多線程的。 你正在創建一個綁定在一個端口上的線程,然後從任何客戶端套接字讀取,直到連接關閉。

您需要將套接字傳遞給一個新的線程並讀取它。

public class DoSomethingWithInput implements Runnable {
   private final Socket clientSocket; //initialize in const'r
   public void run() {

        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String nextline;
        while ((nextline = in.readLine())!=null) {
           System.out.println(nextline);
        } //... close socket, etc.
    }
}

//...
ServerSocket serverSocket = null;
serverSocket = new ServerSocket(5432);
for (;;) {
    Socket clientSocket = null;
    clientSocket = serverSocket.accept();
    //delegate to new thread
    new Thread(new DoSomethingWithInput(clientSocket)).start();
} //...

Question

我試圖通過多線程來適應我的簡單的套接字服務器,以便它可以有多個TCP連接,但我似乎無法得到它的工作。 我的代碼到目前為止,我不知道從哪裡去:

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

public class DoSomethingWithInput implements Runnable {
   private final Socket clientSocket; //initialize in const'r
   public void run() {


     BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String nextline;
        while ((nextline = in.readLine())!=null) {
           System.out.println(nextline);
        } //... close socket, etc.
    }
}


public class Socket{

  public Socket() {
}
@Override
public void run() {
  try {
    ServerSocket serverSocket = null;
    serverSocket = new ServerSocket(5432);
    for (;;) {
      ServerSocket serverSocket = null;
      serverSocket = new ServerSocket(5432);
      for (;;) {
        Socket clientSocket = null;
        clientSocket = serverSocket.accept();
        //delegate to new thread
        new Thread(new DoSomethingWithInput(clientSocket)).start();
      }
    }
  }catch (IOException e) {
   System.err.println("Could not listen on port: 5432.");
   System.exit(1);
}
}
}

任何人都可以給我一些關於如何做到這一點,以及為什麼我目前的實施將無法工作的指針? 我正在運行Java教程http://download.oracle.com/javase/tutorial/networking/sockets/examples/KKMultiServerThread.java中的提示,但是這裡給出的例子似乎使用了很多外部源,像KnockKnockProtocol等類

任何人都可以幫助我嗎?

非常感謝你!