服務器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();
}
}