server.java

来自「此源码为机械工业出版社出版的《Java语言程序设计》第三版所配套的书中所有源代码」· Java 代码 · 共 54 行

JAVA
54
字号
// Server.java: The server accepts data from the client, processes it
// and returns the result back to the client
import java.io.*;
import java.net.*;

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

      // Start listening for connections on the server socket
      Socket connectToClient = serverSocket.accept();

      // Create an input stream to get data from the client
      DataInputStream isFromClient = new DataInputStream(
        connectToClient.getInputStream());

      // Create an output stream to send data to the client
      DataOutputStream osToClient = new DataOutputStream(
        connectToClient.getOutputStream());

      // Continuously read from the client and process it,
      // and send result back to the client
      while (true)
      {
        // Read a string from the input stream
        double radius = isFromClient.readDouble();

        // Display radius on console
        System.out.println("radius received from client: " + radius);

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

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

⌨️ 快捷键说明

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