Creating Client/Server Applications : JSP Socket « JSP « Java Tutorial






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>

YourServer.java

import java.io.*;
import java.net.*;

public class YourServer
{    
    public static void main(String[] args ) 
    {
        try {    
            ServerSocket socket = new ServerSocket(8765);

            Socket insocket = socket.accept( );

            BufferedReader in = new BufferedReader (new 
                InputStreamReader(insocket.getInputStream()));
            PrintWriter out = new PrintWriter (insocket.getOutputStream(), 
                true);

            String instring = in.readLine();
            out.println("The server got this: " + instring);
            insocket.close();
        }
        catch (Exception e) {} 
     } 
}








23.46.JSP Socket
23.46.1.Creating Client/Server Applications
23.46.2.Use Socket to load a web page