Java Socket編程(3)
發(fā)表時(shí)間:2023-08-12 來(lái)源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要]服務(wù)器Sockets列表9.2是一個(gè)服務(wù)器應(yīng)用程序的一部分.列表9.2 一個(gè)簡(jiǎn)單的服務(wù)器程序 /** * 一個(gè)監(jiān)聽端口并提供HTML文檔的程序.*/ class SimpleWebServer p...
服務(wù)器Sockets
列表9.2是一個(gè)服務(wù)器應(yīng)用程序的一部分.
列表9.2 一個(gè)簡(jiǎn)單的服務(wù)器程序
/**
* 一個(gè)監(jiān)聽端口并提供HTML文檔的程序.
*/
class SimpleWebServer {
public static void main(String args[])
{
ServerSocket serverSocket = null;
Socket clientSocket = null;
int connects = 0;
try
{
{
// 建立一個(gè)服務(wù)器socket
serverSocket = new ServerSocket(80, 5);
while (connects < 5)
{
// 等待連接
clientSocket = serverSocket.accept();
//服務(wù)連接
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());
//格式化輸出(回應(yīng)頭和很少的HTML文檔)
StringBuffer buffer = PrepareOutput();
String inputLine;
while ((inputLine = inbound.readLine()) != null)
{
//如果到了HTTP請(qǐng)求的尾部,就發(fā)送回應(yīng)
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();
}
}