熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java Socket編程(三)服務器Sockets

2022-06-13   來源: Java核心技術 

  服務器Sockets
  列表是一個服務器應用程序的一部分
  列表 一個簡單的服務器程序
  /**
  * 一個監聽端口並提供HTML文檔的程序
  */
  class SimpleWebServer {
  public static void main(String args[])
  {
  ServerSocket serverSocket = null;
  Socket clientSocket = null;
  int connects = ;
  try
  {
  {
  // 建立一個服務器socket
  serverSocket = new ServerSocket( );
  while (connects < 5)
  {
  // 等待連接
  clientSocket = serverSocket.accept();
  //服務連接
  ServiceClient(clientSocket);
  connects++;
  }
  serverSocket.close();
  }
  catch (IOException ioe)
  {
  System.out.println("Error in SimpleWebServer: " + ioe);
  }
  }
  public static void ServiceClient(Socket client)
  throws IOException
  {
  DataInputStream inbound = null;
  DataOutputStream outbound = null;
  try
  {
  // 得到IO流
  inbound = new DataInputStream( client.getInputStream());
  outbound = new DataOutputStream( client.getOutputStream());
  //格式化輸出(回應頭和很少的HTML文檔)
  StringBuffer buffer = PrepareOutput();
  String inputLine;
  while ((inputLine = inbound.readLine()) != null)
  {
  //如果到了HTTP請求的尾部,就發送回應
  if ( inputLine.equals("") )
  {
  outbound.writeBytes(buffer.toString());
  break;
  }
  }
  }
  finally
  {
  // 清除
  System.out.println("Cleaning up connection: " + client);
  tln("Cleaning up connection: " + client);
  outbound.close();
  inbound.close();
  client.close();
  client.close();
  }
  }
  

From:http://tw.wingwit.com/Article/program/Java/hx/201311/27131.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.