對socket還是不太了解,但下面這組程式,可以建立一個可以回應伺服器(名詞不確定)。但別人輸入ip及port時,會回傳資料。有點類似一個api。
public static void httpSocket(int port, String ip) throws IOException {
InetAddress addr = InetAddress.getByName(ip);
ServerSocket serverSocket = new ServerSocket(port, 50, addr);
System.err.println("Server port : " + port);
try {
while (true) {
java.net.Socket clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
String s;
while ((s = in.readLine()) != null) {
System.out.println(s);
if (s.isEmpty()) {
break;
}
}
System.err.println("4");
out.write("HTTP/1.0 200 OK\r\n");
out.write("Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n");
out.write("Server: Apache/0.8.4\r\n");
out.write("Content-Type: text/html\r\n");
out.write("Content-Length: 59\r\n");
out.write("Expires: Sat, 01 Jan 2000 00:59:59 GMT\r\n");
out.write("Last-modified: Fri, 09 Aug 1996 14:21:40 GMT\r\n");
out.write("\r\n");
out.write("<TITLE>Exemple</TITLE>");
out.write("<P>Ceci est une page d'exemple.</P>");
System.err.println("5");
System.err.println("Connexion avec le client terminée");
out.close();
in.close();
clientSocket.close();
}
} catch (Exception e) {
System.out.println(e);
e.getStackTrace();
} finally {
serverSocket.close();
}
}
留言列表