从本地计算机连接到 ServerSocket

发布于 2024-11-19 19:59:36 字数 1108 浏览 3 评论 0原文

我对 java 相当陌生,目前正在尝试套接字和缓冲区。

我想尝试的只是实例化一个本地 java 应用程序和另一个本地 java 应用程序的连接。我正在使用 ServerSocket 和 Socket。

服务器应用程序有一个侦听连接的线程:

    public void run() {

    try{

        ServerSocket serverSock = new ServerSocket(62666);

        while(doRun){

            Socket sock = serverSock.accept();
            BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));

            InfoReader.gui.writeToTextArea(reader.readLine() + "\n");



            reader.close();

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

}

“客户端”只是将一个字符串发送到服务器(应该是这样,但我无法使其工作):

try{
        Socket sock = new Socket("127.0.0.1",62666); 
        PrintWriter writer = new PrintWriter(sock.getOutputStream());
        writer.print("Connection works!");
    }catch(IOException e){
        e.printStackTrace();
    }

我确信端口已打开并转发到本地机器已经。我检查过 http://canyouseeme.org/

我还尝试使用我的外部 IP 地址作为客户端中套接字的 IP。它也不起作用。

任何帮助表示赞赏:)。

麦克风。

I am fairly new to java and I am currently experimenting with sockets and buffers.

What I wanted to try was just to instantiate a connection from one local java app and another. I am using ServerSocket and Socket.

The server app has a thread that listens for connections:

    public void run() {

    try{

        ServerSocket serverSock = new ServerSocket(62666);

        while(doRun){

            Socket sock = serverSock.accept();
            BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));

            InfoReader.gui.writeToTextArea(reader.readLine() + "\n");



            reader.close();

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

}

The "client" simply sends a string to the server (well it should, but I can't make it work):

try{
        Socket sock = new Socket("127.0.0.1",62666); 
        PrintWriter writer = new PrintWriter(sock.getOutputStream());
        writer.print("Connection works!");
    }catch(IOException e){
        e.printStackTrace();
    }

I am sure that the port is open and forwarded to the local machine already. I've checked on http://canyouseeme.org/.

I've also tried using my external IP address as the IP of the socket in the client. It did not work either.

Any help appreciated :).

Mike.

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

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

发布评论

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

评论(1

愁以何悠 2024-11-26 19:59:36

好的,然后作为答案,这样您就可以关闭问题;-)

向 Writer 添加一个flush()和一个close()。

希望有帮助。 :-)

Ok, then as an answer so you can close the question ;-)

Add a flush() and a close() to the Writer.

Hope that helps. :-)

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