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



0 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等。

有人能幫我解決這個問題嗎?

非常感謝你!




Related



Tags

java java   sockets