Java - 通过浏览器/URL 连接到 ServerSocket

发布于 2024-11-24 18:53:30 字数 1676 浏览 3 评论 0 原文

我正在编写一个软件,并且受到无法使用套接字连接到使用 ServerSocket 的 java 应用程序的限制。

我想我应该尝试使用 URL 连接,因为可以定义要连接到的端口,

例如:

127.0.0.1:62666

我有我的服务器应用程序侦听连接并将输入写入 jTextArea。当通过浏览器连接到服务器(127.0.0.1:62666)时,它输出:

GET / HTTP/1.1
GET /favicon.ico HTTP/1.1

我有另一个应用程序用于通过 URL 连接连接到 ServerSocket:

try{
        URL url = new URL("http://127.0.0.1:62666");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.connect();
        PrintWriter writer = new PrintWriter(connection.getOutputStream());
        writer.print("Hello");
        System.out.println("should have worked");
        writer.flush();
        writer.close();
    }catch(IOException e){
        e.printStackTrace();
    }

它打印出“应该有效”消息仅供参考,但它从不写入任何内容到服务器的 jTextArea。服务器应用程序的代码如下所示:

try{

        ServerSocket serverSock = new ServerSocket(62666);

        while(doRun){
            Socket sock = serverSock.accept();
            BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            PrintWriter writer = new PrintWriter(sock.getOutputStream());

            InfoReader.gui.writeToTextArea(reader.readLine() + " From IP: " + sock.getInetAddress() + "\n");
            writer.println("Testing123");

            writer.close();

            reader.close();

        }
    }catch(IOException e){
        e.printStackTrace();
    }

注意:通过浏览器连接时,它会显示文本“Testing123”。

所以我想知道如何按照我尝试的方式执行此操作,或者读取访问 ServerSocket 所通过的 URL,以便我可以通过 URL 访问它,同时传递参数(在 URL 中)。

希望这是有道理的:)

谢谢, 麦克风。

I'm writing a piece of software, and I'm under the restriction of not being able to use socket to connect to a java application using a ServerSocket.

I thought I'd try with an URL connection, since it's possible to define which port to connect to

e.g:

127.0.0.1:62666

I have my server app listening for connections and writing the input out to a jTextArea. When connecting to the server (127.0.0.1:62666) through a browser, it outputs:

GET / HTTP/1.1
GET /favicon.ico HTTP/1.1

I have another app for connecting to the ServerSocket through an URL connection:

try{
        URL url = new URL("http://127.0.0.1:62666");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.connect();
        PrintWriter writer = new PrintWriter(connection.getOutputStream());
        writer.print("Hello");
        System.out.println("should have worked");
        writer.flush();
        writer.close();
    }catch(IOException e){
        e.printStackTrace();
    }

It prints out the "should have worked" message fyi, but it never writes anything to the jTextArea of the server. The code for the server app looks like this:

try{

        ServerSocket serverSock = new ServerSocket(62666);

        while(doRun){
            Socket sock = serverSock.accept();
            BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            PrintWriter writer = new PrintWriter(sock.getOutputStream());

            InfoReader.gui.writeToTextArea(reader.readLine() + " From IP: " + sock.getInetAddress() + "\n");
            writer.println("Testing123");

            writer.close();

            reader.close();

        }
    }catch(IOException e){
        e.printStackTrace();
    }

Note: when connecting through the browser it displays the text "Testing123".

So I'm wondering how to do this the way I'm trying or perhaps read the URL that the ServerSocket was accessed through, so I could access it through a URL while passing it arguments (in the URL).

Hope this makes sense :)

Thanks,
Mike.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

您的好友蓝忘机已上羡 2024-12-01 18:53:30

有一个非常好的 示例

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"));
            }
        }
    }
}

转到http://127.0.0.1:8080/,您将获得当前日期。

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.

暖心男生 2024-12-01 18:53:30

我无法弄清楚究竟发生了什么。这个 OutputStream 有一些有趣的地方。 在 connect() 之后和 close() 之前添加一个

((HttpURLConnection) connection).getResponseCode();

,您应该会看到不同的内容,即使不是您所期望的。

也许您不应该尝试使用 HTTP 作为 hack,而应该使用完整的 HTTP。像以前一样从客户端使用 HTTP,并在服务器上设置嵌入式 HTTP 服务器。有几个可供选择,实际上只需要几行即可运行: Grizzly简单框架Jetty。

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.

梦在深巷 2024-12-01 18:53:30

我认为如果您希望客户端使用 URL 连接向服务器发送消息,您需要执行以下操作:

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();}
    }
}

现在这是服务器:

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;
}

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;
}
情愿 2024-12-01 18:53:30
writer.println("Hello");

您没有发送任何换行符。此外,您的“应该有效”跟踪位于错误的位置。应该在flush()之后。

而且您没有阅读回复。

此外,服务器只会显示 POST ... 或 PUT ...,而不是您发送的行。因此,除非您(a)使服务器具有 HTTP 意识或(b)摆脱无法使用 Socket 的疯狂限制,否则这永远不会起作用。 为什么不能使用套接字?

编辑:我的代码版本如下:

    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");
    }
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");
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文