龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > JAVA开发 >

Java Socket编程(三)

时间:2009-12-23 15:42来源:未知 作者:admin 点击:
分享到:
服务器Sockets 列表9.2是一个服务器应用程序的一部分. 列表9.2 一个简单的服务器程序 /** * 一个监听端口并提供Html文档的程序. */ class SimpleWebServer { public static void main(String args[]) { ServerS

  服务器Sockets
  
  列表9.2是一个服务器应用程序的一部分.
  
  列表9.2 一个简单的服务器程序
  
  /**
  * 一个监听端口并提供Html文档的程序.
  */
  class SimpleWebServer {
  public static void main(String args[])
  {
  ServerSocket serverSocket = null;
  Socket clientSocket = null;
  int connects = 0;
  try
  {
  {
  // 建立一个服务器socket
  serverSocket = new ServerSocket(80, 5);
  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();
  }
  }
  
精彩图集

赞助商链接