将套接字连接到服务器并接收响应

时间:2015-03-13 01:20:49

标签: java sockets proxy network-programming

我正在编写一个简单的多线程java代理,但我似乎无法让服务器显示我所说的内容,或者发回任何内容。这是我的代码:

    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       
    }

我与服务器的大部分通信都发生在TcpServerThread类中,我正在尝试使用TcpClient类与服务器通信,发送HTTP请求,并打印出服务器发回的内容,尽管我之后输入一个http请求,它只解析它然后只是空白。任何帮助将非常感激。

1 个答案:

答案 0 :(得分:0)

您正在呼叫writeUTF(),但没有人正在呼叫readUTF().这是任何人都能理解所写内容的唯一方式。

此代理无法运行。一旦创建了初始连接,每个连接需要两个线程,一个用于每个方向的读写。您不能假设在一次读取中读取请求或响应,并且通常不能假设存在单个请求/响应对,或者实际上任何类似请求或响应的内容。