简体   繁体   中英

Connecting Socket to Server and Receiving a Response

I'm writing a simple multi threaded java proxy, but I can't seem to get the server to display what I said, or send anything back. Here is my code:

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

    public class TcpClient {

        public static void clientS( int portNumber, String request) throws Exception {
            String sentence = "";
            String modifiedSentence = "";

            System.out.println("In client class..");

            BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
            Socket clientSocket = new Socket("localhost", portNumber);
            DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

            outToServer.writeUTF(modifiedSentence);
            System.out.println("What got written to the server: "+request);

            BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            sentence = inFromUser.readLine();
            outToServer.writeBytes(sentence + '\n');
            modifiedSentence = inFromServer.readLine();
            clientSocket.close();

            //TcpServerThread tcpThread = new TcpServerThread(clientSocket);
            //tcpThread.run();
        }//end method

    }// client class

    import java.net.Socket;
    import java.util.Scanner;
    import java.util.StringTokenizer;


    public class RequestParser extends TcpServerThread{

        static String method = "";
        static String endUrl = "";
        static String version = "";
        static String hostHeader = "";
        static String host = "";
        static String hostHeader1 = "";
        static String host1 = "";
        static String hostHeader2 = "";
        static String host2 = "";



        public RequestParser(Socket theSocket) {
            super(theSocket);
        }

        static int portNumber = 80;

        public int Request() {

            Scanner scan = new Scanner(System.in);
            System.out.println("Please type in your information, with headers separated by a space: ");
            String request = scan.nextLine();//stores the HTTP request

            //parses the HTTP request, gets port number if there is one
            try {
                portNumber = doFormattedMethodRequest(request);
                TcpClient.clientS(portNumber, request);
            } catch (Exception e) {
                e.getMessage();
            }
            return portNumber;

        }//end method

        public static int doFormattedMethodRequest(String unformattedRequest) throws Exception{


            System.out.println("In String Parser...");
            StringTokenizer tokenizer = new StringTokenizer(unformattedRequest," ");
            Scanner scan = new Scanner(System.in);

            //gets method, loops if there isn't correct input

            while (tokenizer.hasMoreElements()){


                method = (String) tokenizer.nextElement();
                System.out.println("method: "+method);
                if (!method.equals("GET")){
                    System.out.println("This program only supports GET requests");
                    System.out.println("Your method has been changed to GET");
                    method = "GET";
                }//end if

                endUrl = (String) tokenizer.nextElement();
                System.out.println("endUrl: "+endUrl);

                if(!endUrl.endsWith(".html")|| !endUrl.endsWith(".com")
                        || !endUrl.endsWith(".edu")||!endUrl.endsWith(".gov")||
                        !endUrl.endsWith(".net")||!endUrl.endsWith(".org")||
                        !endUrl.endsWith(".mil")){

                    String [] parts = endUrl.split("/");

                    for (int i=0;i<parts.length;i++){
                        host = "www."+parts[2];
                        if (parts[i].matches("/*[1-65535].*") == true){

                            String port = parts[i];
                            portNumber = Integer.parseInt(port);

                            System.out.println("Contains a port number");
                            System.out.println("Port Number is: "+portNumber);

                        }//end if   
                    }//end for loop
                }//end if


                version = (String) tokenizer.nextElement();
                System.out.println("version: "+version);
                if (!version.endsWith("1.0")){
                    System.out.println("This program only supports version of 1.0");
                    System.out.println("Your version has been changed to 1.0");
                    version = "1.0";
                }
                System.out.println("host: "+host);      

                hostHeader = (String) tokenizer.nextElement();
                host = (String) tokenizer.nextElement();
                hostHeader1 = (String) tokenizer.nextElement();
                host1 = (String) tokenizer.nextElement();
                hostHeader2 = (String) tokenizer.nextElement();
                host2 = (String) tokenizer.nextElement();


            }//end while loop               


            System.out.println("OK, here is what is being sent to the server...");
            System.out.print(method); System.out.print(" "+endUrl);
            System.out.println(" "+version);
            //System.out.print(hostHeader); System.out.println(host+endUrl);
            //System.out.print(hostHeader1); System.out.print(host);
            //System.out.println(hostHeader);System.out.println(host);

            return portNumber;



        }//end method

    }//end class

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

    class TcpServerThread extends Thread{

        static Socket connectionSocket = null;
        static int portNumber = 0;

        public TcpServerThread(Socket theSocket){
            super("TcpServerThread");
            TcpServerThread.connectionSocket = theSocket;
        }

        public static void main(String args[]) {

            System.out.println("Taking you to HTTP request input...");
            RequestParser estProxy = new RequestParser(connectionSocket);

            portNumber = estProxy.Request();//goes to get the user's http request
            System.out.println("");
            System.out.println("-----------------------------------------------------");
            System.out.println("System returned "+portNumber+" as the port number.");


            //create listener socket to listen for requests
            ServerSocket welcomeSocket;
            try {
                welcomeSocket = new ServerSocket(portNumber);
            System.out.println("");

            System.out.println("Listening on port number "+portNumber+"...");

            estProxy.run(); 

            boolean isListening = true;
            while (isListening) {
                new TcpServerThread(welcomeSocket.accept()).start();
            }//end while

            } catch (Exception e) {
                e.getMessage();
            }

        }//end method


        public void run(){
            System.out.println("Got into run method");

            Socket serverSocket = new Socket();
            Socket clientSocket = new Socket();

            try{
                InputStream inStream = clientSocket.getInputStream();
                byte [] buf = new byte[9000];

                int length = inStream.read(buf);

                System.out.println(new String(buf,0,length));   

                Socket socket= new Socket("localhost",portNumber);
                OutputStream outStream = socket.getOutputStream();
                outStream.write(buf,0,length);

                OutputStream inStream1 = clientSocket.getOutputStream();
                InputStream outStream1 = socket.getInputStream();
                for(int length1; (length1 = outStream1.read(buf)) != -1;){
                    inStream1.write(buf,0,length1);
                }

                inStream1.close();
                outStream1.close();
                outStream.close();
                inStream.close();
                socket.close();

            }
            catch(Exception e){
                e.getMessage();
            }
            finally{
                try{
                    clientSocket.close();
                }
                catch(IOException e){
                    e.getMessage();
                }
            }
        }//end method       
    }

Most of my communication with the server is happening in the TcpServerThread class, and I'm trying to use the TcpClient class to talk to the server, send an HTTP request, and print out what the server sends back, although after I input an http request, it only parses it and then just goes blank. Any help would be much appreciated.

You're calling writeUTF() but nobody is calling readUTF(). That's the only way anyone will understand what is written.

Howver this proxy won't work. Once you've created the initial connections you need two threads per connection, one to read and write in each direction. You can't assume that the request or response are read in a single read, and you can't generally assume that there is a single request/response pair, or indeed anything like a request or response at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM