📄 exercise20_1server.java
字号:
// Exercise20_1Server.java: The server can communicate with// multiple clients concurrently using the multiple threadsimport java.io.*;import java.net.*;import java.util.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Exercise20_1Server extends JFrame { private JTextArea jta = new JTextArea(); public static void main(String[] args) { new Exercise20_1Server(); } public Exercise20_1Server() { getContentPane().setLayout(new BorderLayout()); getContentPane().add(new JScrollPane(jta), BorderLayout.CENTER); jta.setWrapStyleWord(true); jta.setLineWrap(true); setTitle("Exercise20_1Server"); setSize(500, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); try { ServerSocket serverSocket = new ServerSocket(8000); jta.append("Exercise20_1Server started at " + new Date() + '\n'); int clientNo = 1; while (true) { Socket connectToClient = serverSocket.accept(); jta.append("Starting thread for client " + clientNo + " at " + new Date() + '\n'); InetAddress clientInetAddress = connectToClient.getInetAddress(); jta.append("Client " + clientNo + "'s host name is " + clientInetAddress.getHostName() + "\n"); jta.append("Client " + clientNo + "'s IP Address is " + clientInetAddress.getHostAddress() + "\n"); HandleAClient thread = new HandleAClient(connectToClient); thread.start(); clientNo++; } } catch(IOException ex) { System.err.println(ex); } } class HandleAClient extends Thread { private Socket connectToClient; public HandleAClient(Socket socket) { connectToClient = socket; } public void run() { try { DataInputStream isFromClient = new DataInputStream( connectToClient.getInputStream()); DataOutputStream osToClient = new DataOutputStream( connectToClient.getOutputStream()); while (true) { double length = isFromClient.readDouble(); double width = isFromClient.readDouble(); double high = isFromClient.readDouble(); double area = 2*((length * width)+(width * high)+(high * length)); double volume = length * width * high; osToClient.writeDouble(area); osToClient.writeDouble(volume); jta.append("Length: " + length + " Width: " + width + " High: " + high + "\n"); jta.append(" Area: " + area + " " + " Volume: " + volume + '\n'); } } catch(IOException e) { System.err.println(e); } } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -