服務器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