【问题标题】:Multithreaded Server using TCP in JavaJava中使用TCP的多线程服务器
【发布时间】:2011-10-10 16:30:36
【问题描述】:

我正在尝试在客户端/服务器之间实现一个简单的 TCP 连接。我使服务器多线程,以便它可以接受来自单个客户端的多个请求(例如查找用户提供的一串数字的总和、最大值、最小值)或接受来自不同客户端的多个连接。我在我的机器上运行它们,但服务器似乎没有给出答案。不知道我在这里做错了什么--

public final class CalClient {

static final int PORT_NUMBER = 6789;  

public static void main (String arg[]) throws Exception
{
    String serverName;
    @SuppressWarnings("unused")
    String strListOfNumbers = null;
    int menuIndex;
    boolean exit = false;

    BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

    System.out.println("Please enter host name...");
    System.out.print("> ");
    serverName = inFromUser.readLine();

    Socket clientSocket = new Socket(serverName, PORT_NUMBER);
    DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
    BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

    //outToServer.writeBytes(serverName + '\n');

    System.out.println("");
    System.out.println("Enter 1 to enter the list of numbers");
    System.out.println("Enter 2 to perform Summation");
    System.out.println("Enter 3 to calculate Maximum");
    System.out.println("Enter 4 to calculate Minimum");
    System.out.println("Enter 5 to Exit");

    while (!exit) {
        System.out.print(">");
        menuIndex = Integer.parseInt(inFromUser.readLine());

        if (menuIndex == 1) {   
            System.out.println("Please enter the numbers separated by commas.");
            System.out.print(">");
            strListOfNumbers = inFromUser.readLine();
            outToServer.writeBytes("List" + strListOfNumbers);
            //continue;
        }
        else if (menuIndex == 2) {
            outToServer.writeBytes("SUM");
            System.out.println(inFromServer.readLine());
        }
        else if (menuIndex == 3) {
            outToServer.writeBytes("MAX");
            System.out.println(inFromServer.readLine());
        }
        else if (menuIndex == 4) {
            outToServer.writeBytes("MIN");
            System.out.println(inFromServer.readLine());
        }
        else if (menuIndex == 5) {
            outToServer.writeBytes("EXIT");
            exit = true;
        }
    }
}

}

public final class CalServer 
{

      static final int PORT_NUMBER = 6789;  

public static void main(String[] args) throws IOException 
{
    try {
        ServerSocket welcomeSocket = new ServerSocket(PORT_NUMBER);
        System.out.println("Listening");
        while (true) {
            Socket connectionSocket = welcomeSocket.accept();

            if (connectionSocket != null) {
                CalRequest request = new CalRequest(connectionSocket);
                Thread thread = new Thread(request);
                thread.start();
            }
        }
    } catch (IOException ioe) {
        System.out.println("IOException on socket listen: " + ioe);
        ioe.printStackTrace();
    }
}
}

final class CalRequest implements Runnable
{
Socket socket;
BufferedReader inFromClient;
DataOutputStream outToClient;

TreeSet<Integer> numbers = new TreeSet<Integer>();
int sum = 0;

public CalRequest(Socket socket)
{
    this.socket = socket;
}

@Override
public void run() 
{
    try {
        inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
        outToClient = new DataOutputStream(socket.getOutputStream());

        while(inFromClient.readLine()!= null) {
            processRequest(inFromClient.readLine());
        }       

    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void processRequest(String string) throws IOException
{
    String strAction = string.substring(0,3);

    if (strAction.equals("LIS")) {
        String strNumbers = string.substring(5);
        String[] strNumberArr;
        strNumberArr = strNumbers.split(",");

        // convert each element of the string array to type Integer and add it to a treeSet container. 
        for (int i=0; i<strNumberArr.length; i++)
            numbers.add(new Integer(Integer.parseInt(strNumberArr[i])));
    }
    else if (strAction.equals("SUM")) {
        @SuppressWarnings("rawtypes")
        Iterator it = numbers.iterator();
        int total = 0;

        while (it.hasNext()) {
            total += (Integer)(it.next());
        }
    }
    else if (strAction.equals("MAX")) {
        outToClient.writeBytes("The max is: " + Integer.toString(numbers.last()));
    }
    else if (strAction.equals("MIN")) {
        outToClient.writeBytes("The max is: " + Integer.toString(numbers.first()));
    }
}

}

【问题讨论】:

  • 找不到问题...
  • 对不起,我正在编辑它。

标签: multithreading tcp client-server localhost


【解决方案1】:

由于您使用的是readLine(),我猜您实际上需要发送线路终止符。

【讨论】:

  • 您的意思是回车/换行序列 ("\r\n")、单个回车 ("\r") 或单个换行 ("\n “)?那么当我向服务器写入字节时,我会连接它吗?
  • 我将 \r\n 添加到客户端,但没有任何区别。当我为 MAX 输入 3 时,它会在 java.util.TreeMap.key(Unknown Source) at java.util.TreeMap.lastKey(Unknown Source) 的线程“Thread-0”java.util.NoSuchElementException 中引发以下异常异常在 java.util.TreeSet.last(Unknown Source) 在 CalRequest.processRequest(CalServer.java:84) 在 CalRequest.run(CalServer.java:53) 在 java.lang.Thread.run(Unknown Source)
  • 45 次查看但没有答案,太好了。
  • 通常导致这种情况的另一件事是您需要在写入某些内容后刷新套接字。否则,它只会等待更多数据到达,以便可以大量发送。我真的不知道这是否是这里的问题;某些环境在遇到换行符时会自动刷新,但绝对值得一试。
【解决方案2】:

我的 TCP 套接字通信经验专门使用 ASCII 数据,我的代码反映了我的看法。如果你是这种情况,你可能想试试这个:

首先,尝试像这样实例化您的数据流:

socket     = new Socket (Dest, Port);
toServer   = new PrintWriter (socket.getOutputStream(), true);
fromServer = new BufferedReader (new InputStreamReader
    (socket.getInputStream()), 8000);

printWriter 构造函数末尾的 true 告诉它在您发出 println 时自动刷新(可爱的术语)缓冲区。

实际使用socket时,使用如下:

toServer.println (msg.trim());
resp = fromServer.readLine().trim();

我自己不必将 \n 附加到传出文本中,但这可能与我的具体情况有关(更多内容见下文)。传入的数据需要在其末尾有一个 \n 或 readLine 不起作用。我假设您可以通过多种方式逐字节读取套接字,但代码也不会那么简单。

不幸的是,我正在与之通信的 TCP 服务器是一个 C++ 程序,因此我们确保传入数据中存在 \n 的方式对您不起作用(并且在传出数据中可能不需要) .

最后,如果有帮助,我会根据这个 web 示例构建我的代码:

http://content.gpwiki.org/index.php/Java:Tutorials:Simple_TCP_Networking

编辑:我发现了另一个使用 DataOutputStream 的代码示例...假设您还没有看过它,您可能会发现它很有帮助。

http://systembash.com/content/a-simple-java-tcp-server-and-tcp-client/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多