服務器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 <
{
// 等待連接
clientSocket = serverSocket
//服務連接
ServiceClient(clientSocket);
connects++;
}
serverSocket
}
catch (IOException ioe)
{
System
}
}
public static void ServiceClient(Socket client)
throws IOException
{
DataInputStream inbound = null;
DataOutputStream outbound = null;
try
{
// 得到IO流
inbound = new DataInputStream( client
outbound = new DataOutputStream( client
//格式化輸出(回應頭和很少的HTML文檔)
StringBuffer buffer = PrepareOutput();
String inputLine;
while ((inputLine = inbound
{
//如果到了HTTP請求的尾部
if ( inputLine
{
outbound
break;
}
}
}
finally
{
// 清除
System
tln(
outbound
inbound
client
client
}
}
}
服務器Sockets
服務器並不是主動地建立連接
ServerSocket serverSocket = new ServerSocket(
第一個參數是服務器要監聽的端口
ServerSocket serverSocket = new ServerSocket(
一旦socket建立了並開始監聽連接
Socket clientSocket = serverSocket
這個方法返回一個用來與來訪者對話的客戶端連接
與客戶端socket一樣
DataInputStream inbound = new DataInputStream( clientSocket
DataOutputStream outbound = new DataOutputStream( clientSocket
一般的I/O操作可以在新建的流中運用
所有的服務器都要有以下的基本的步驟
From:http://tw.wingwit.com/Article/program/Java/hx/201311/27218.html