import java.io.BufferedInputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class Server implements Runnable { ServerSocket serverSocket; public static void main(String[] args) throws IOException { new Thread(new Server()).start(); } public Server() { try { serverSocket = new ServerSocket(7777); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { Socket socket; BufferedInputStream inputStream; System.out.println("伺服器已經啟動"); while (true) { socket = null; try { synchronized (serverSocket) { socket = serverSocket.accept(); } socket.setSoTimeout(15000); inputStream = new BufferedInputStream(socket.getInputStream()); byte[] b = new byte[1024]; String data = ""; int length; while ((length = inputStream.read(b)) > 0) { data = new String(b, 0, length); } if (data.equals("Exit")) { inputStream.close(); inputStream = null; socket.close(); serverSocket.close(); System.out.println("伺服器已關閉"); break; } else { System.out.println(data); inputStream.close(); inputStream = null; socket.close(); } } catch (IOException e) { e.printStackTrace(); } } } }