simpleserver.java

来自「《JAVA分布式程序设计》一书的源代码。」· Java 代码 · 共 70 行

JAVA
70
字号
import java.io.*;import java.net.*;/** * @(#)SimpleServer.java * @author Qusay H. Mahmoud */public class SimpleServer {  public final static int TESTPORT = 5000;  public static void main(String args[]) {    // declaration section:    // declare a server socket and a client socket for the server    // declare an input and an output stream    ServerSocket checkServer = null;    String line;    BufferedReader is = null;    DataOutputStream os = null;    Socket clientSocket = null;               // Try to open a server socket on port TESTPORT    // Note that you can't choose a port less than 1023 if you are not    // privileged users (root)    try {       checkServer = new ServerSocket(TESTPORT);       System.out.println("SimpleServer started.....");    } catch (IOException e) {       System.out.println(e);    }       // Create a socket object from the ServerSocket to listen and accept     // connections.    // Open input and output streams    try {       clientSocket = checkServer.accept();       is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));       os = new DataOutputStream(clientSocket.getOutputStream());    } catch(Exception ei) {       ei.printStackTrace();    }    // receive client's greetings and check it contains "Greetings".    try {      line=is.readLine();      System.out.println("we received: "+line);      if (line.compareTo("Greetings") == 0) {	os.writeBytes("...and saluation...");      } else {	 os.writeBytes("sorry, you don't speak my protocol");      }    } catch (IOException e) {       System.out.println(e);    }    // close the i/o streams and the connection    try {       os.close();       is.close();       clientSocket.close();    } catch(IOException ic) {       ic.printStackTrace();    }  }}

⌨️ 快捷键说明

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