Java Tutorial/JSP/JSP Socket

Материал из Java эксперт
Версия от 17:44, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Creating Client/Server Applications

Jsp page



<%@ page import="java.io.*, java.net.*" %>
<HTML>
    <HEAD>
        <TITLE>Creating Client/Server Applications</TITLE>
    </HEAD>
    <BODY>
        <H1>Creating Client/Server Applications</H1>
        <% 
        try{
            int character;
            Socket socket = new Socket("127.0.0.1", 8765);
            InputStream inSocket = socket.getInputStream();
            OutputStream outSocket = socket.getOutputStream();
            String str = "Hello!\n";
            byte buffer[] = str.getBytes();
            outSocket.write(buffer);
            while ((character = inSocket.read()) != -1) {
                out.print((char) character);
            }
            socket.close();
        }
        catch(java.net.ConnectException e){
        %>
            You must first start the server application 
            (YourServer.java) at the command prompt.
        <%
        }
        %>
    </BODY>
</HTML>





Use Socket to load a web page

<%@ page contentType="text/html" import="java.io.*, java.net.*" %>
<% 
        try {
            Socket s = new Socket("www.jexp.ru", 80);
            BufferedReader in = new BufferedReader(new 
                InputStreamReader(s.getInputStream()));
            PrintWriter socketOut = new PrintWriter(s.getOutputStream());
            socketOut.print("GET /index.html\n\n");
            socketOut.flush();
            String line;
            while ((line = in.readLine()) != null){
                out.println(line);
            }
        } catch (Exception e){}
%>