简体   繁体   English

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

[英]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. 我正在编写一个简单的多线程Java代理,但是似乎无法让服务器显示我所说的内容或将任何内容发回。 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. 我与服务器的大多数通信都是在TcpServerThread类中进行的,尽管我输入了http,但我正在尝试使用TcpClient类与服务器进行对话,发送HTTP请求并打印出服务器发回的内容。请求,它只会解析它,然后变成空白。 Any help would be much appreciated. 任何帮助将非常感激。

You're calling writeUTF() but nobody is calling readUTF(). 您正在调用writeUTF()但没有人在调用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. 您不能假设请求或响应是在一次读取中读取的,并且通常不能假设存在单个请求/响应对,或者根本不存在像请求或响应之类的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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