Java - connection to ServerSocket via browser/URL

烂漫一生 提交于 2019-12-06 12:46:19

I can't figure out exactly what's up. There's something funny about that OutputStream. Add a

((HttpURLConnection) connection).getResponseCode();

somewhere after connect() and before close(), and you should see something different, if not what you expect.

Perhaps instead of trying to use HTTP as a hack, you should just go full HTTP. Use HTTP from the client like you already are, and set up an embedded HTTP server on the server. There are several to choose from out there that literally take just a few lines to get running: Grizzly, Simple Framework, or Jetty, for instance.

There is one very good example:

public class SimpleHTTPServer {
    public static void main(String args[]) throws IOException {
        ServerSocket server = new ServerSocket(8080);
        while (true) {
            try (Socket socket = server.accept()) {
                Date today = new Date();
                String httpResponse = "HTTP/1.1 200 OK\r\n\r\n" + today;
                socket.getOutputStream().write(httpResponse.getBytes("UTF-8"));
            }
        }
    }
}

Go to http://127.0.0.1:8080/ from browser and you'll get current date.

I think this is what you need to do if you want the client to send a message to the server using a URL connection:

public class Client
{
    public Client()
    {
        try
        {
            url = new URL("http://127.0.0.1:62666");
            URLConnection urlConnection = url.openConnection();
            PrintWriter writer = new PrintWriter(urlConnection.getOutputStream());
            writer.println("Hello World!");
            writer.flush();
            writer.close();
        }catch(Exception e){e.printStackTrace();}
    }
}

Now heres the server:

public class Server implements Runnable
{
    public Server()
    {
        ServerSocket server = new Server(62666);
        client = server.accept();
        new Thread(this).start();  
    }

    public void run()
    {
        try
        {
            String message;
            BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()))
            while((message=reader.readLine())!=null)
            {
                System.out.println("Message from client: "+message);
            }
        }catch(Exception e)
        {
            System.out.println("Client disconnected");
        }
    }
    Socket client;
}
writer.println("Hello");

You're not sending any newline. Also your 'should have worked' trace is in the wrong place. Should be after the flush().

Also you aren't reading the response.

Also the server is only going to display POST ... Or PUT ..., not the line you're sending. So this is never going to work unless you (a) make the server HTTP-conscious or (b) get rid of this insane restriction that you can't use a Socket. Why can't you use a Socket?

EDIT: my version of your code follows:

    static class Server implements Runnable
    {

        public void run()
        {
            try
            {
                ServerSocket serverSock = new ServerSocket(62666);
                for (;;)
                {
                    Socket sock = serverSock.accept();
                    System.out.println("From IP: " + sock.getInetAddress());
                    BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
                    PrintWriter writer = new PrintWriter(sock.getOutputStream());
                    String line;
                    while ((line = reader.readLine()) != null)
                    {
                        System.out.println("\t:" + line);
                    }
                    writer.println("Testing123");
                    writer.close();
                    reader.close();
                    System.out.println("Server exiting");
                    serverSock.close();
                    break;
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    static class Client implements Runnable
    {

        public void run()
        {
            try
            {
                URL url = new URL("http://127.0.0.1:62666");
                HttpURLConnection connection = (HttpURLConnection)url.openConnection();
                connection.setDoOutput(true);
//              connection.setRequestMethod("POST");
                connection.connect();
                PrintWriter writer = new PrintWriter(connection.getOutputStream());
                writer.println("Hello");
                writer.flush();
                System.out.println("flushed");
                int responseCode = connection.getResponseCode();
                writer.close();
                BufferedReader  reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                System.out.println("closed");
                System.out.println("response code="+responseCode);
                String  line;
                while ((line = reader.readLine()) != null)
                    System.out.println("client read "+line);
                reader.close();
                System.out.println("Client exiting");
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    public static void  main(String[] args)
    {
        Thread  t = new Thread(new Server());
        t.setDaemon(true);
        t.start();
        new Client().run();
        System.out.println("Main exiting");
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!