⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 multithreadserver.java

📁 此源码为机械工业出版社出版的《Java语言程序设计》第三版所配套的书中所有源代码。
💻 JAVA
字号:
// MultiThreadsServer.java: The server can communicate with
// multiple clients concurrently using the multiple threads
import java.io.*;
import java.net.*;

public class MultiThreadServer
{
  // Main method
  public static void main(String[] args)
  {
    try
    {
      // Create a server socket
      ServerSocket serverSocket = new ServerSocket(8000);

      // To number a client
      int clientNo = 1;

      while (true)
      {
        // Listen for a new connection request
        Socket connectToClient = serverSocket.accept();

        // Print the new connect number on the console
        System.out.println("Start thread for client " + clientNo);

        // Find the client's hostname, and IP address
        InetAddress clientInetAddress =
          connectToClient.getInetAddress();
        System.out.println("Client " + clientNo + "'s hostname is "
          + clientInetAddress.getHostName());
        System.out.println("Client " + clientNo + "'s IP Address is "
          + clientInetAddress.getHostAddress());

        // Create a new thread for the connection
        HandleAClient thread = new HandleAClient(connectToClient, clientNo);

        // Start the new thread
        thread.start();

        // Increment clientNo
        clientNo++;
      }
    }
    catch(IOException ex)
    {
      System.err.println(ex);
    }
  }
}

// Define the thread class for handling a new connection
class HandleAClient extends Thread
{
  private Socket connectToClient; // A connected socket
  private int clientNo; // Indicate client no

  // Construct a thread
  public HandleAClient(Socket socket, int clientNo)
  {
    connectToClient = socket;
    this.clientNo = clientNo;
  }

  // Implement the run() method for the thread
  public void run()
  {
    try
    {
      // Create data input and output streams
      DataInputStream isFromClient = new DataInputStream(
        connectToClient.getInputStream());
      DataOutputStream osToClient = new DataOutputStream(
        connectToClient.getOutputStream());

      // Continuously serve the client
      while (true)
      {
        // Receive radius from the client
        double radius = isFromClient.readDouble();
        System.out.println("radius received from client " + 
          clientNo + ": " + radius);

        // Compute area
        double area = radius*radius*Math.PI;

        // Send area back to the client
        osToClient.writeDouble(area);
        System.out.println("Area found: " + area);
      }
    }
    catch(IOException ex)
    {
      System.err.println(ex);
    }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -