Java 试图让一个简单的回声客户端服务器程序在两台计算机之间工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20103736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:10:56  来源:igfitidea点击:

Trying to make a simple echo client server program work between two computers

javasocketsnetwork-programmingclient-server

提问by kofhearts

I have been trying to resolve this issue but with no success so finally i am here to get some help from experts.

我一直在尝试解决这个问题,但没有成功,所以最后我在这里寻求专家的帮助。

I just wanted to make a simple client server program work between two computers.

我只是想让一个简单的客户端服务器程序在两台计算机之间工作。

The server will reside in my laptop which is connected to the internet through a linksys router.

服务器将驻留在我的笔记本电脑中,该笔记本电脑通过 linksys 路由器连接到互联网。

The client will reside in a university computer. I scped the file to a university computer and then i run it through ssh.

客户端将驻留在大学计算机中。我将文件 scped 到大学计算机,然后通过 ssh 运行它。

Now also two things worth noting is that i have also disabled firewall in my computer as well as i have configured port forwaring in my linksys router i.e it will forward request to the port to my ipaddress. I have also made my ipadddress static.

现在还有两件值得注意的事情是,我还在我的计算机中禁用了防火墙,并且我在我的 linksys 路由器中配置了端口转发,即它将请求转发到我的 ipaddress 的端口。我也使我的 ipaddaddress 是静态的。

Here is the server code to reside in my laptop.

这是驻留在我的笔记本电脑中的服务器代码。

/* EchoServer.java
 *
 * Copyright (c) 2000 Sean Walton and Macmillan Publishers.  Use may be in
 * whole or in part in accordance to the General Public License (GPL).
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
*/

/*****************************************************************************/
/*** EchoServer.java                                                       ***/
/***                                                                       ***/
/*****************************************************************************/

import java.io.*;
import java.net.*;

public class EchoServer
{
    public EchoServer(int portnum)
    {
        try
        {
            server = new ServerSocket(portnum);
        }
        catch (Exception err)
        {
            System.out.println(err);
        }
    }

    public void serve()
    {
        try
        {
            while (true)
            {

                Socket client = server.accept();

                BufferedReader r = new BufferedReader(new InputStreamReader(client.getInputStream()));
                PrintWriter w = new PrintWriter(client.getOutputStream(), true);
                w.println("Welcome to the Java EchoServer.  Type 'bye' to close.");
                String line;
                do
                {
                    line = r.readLine();
                    if ( line != null )
                        w.println("Got: "+ line);
                }
                while ( !line.trim().equals("bye") );
                client.close();
            }
        }
        catch (Exception err)
        {
            System.err.println(err);
        }
    }

    public static void main(String[] args)
    {
        EchoServer s = new EchoServer(3000);
        s.serve();
    }

    private ServerSocket server;
}

Here is the client code that will reside in university computer.

这是将驻留在大学计算机中的客户端代码。

/* EchoClient.java
 *
 * Copyright (c) 2000 Sean Walton and Macmillan Publishers.  Use may be in
 * whole or in part in accordance to the General Public License (GPL).
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
*/

/*****************************************************************************/
/*** EchoClient.java                                                       ***/
/***                                                                       ***/
/*****************************************************************************/

import java.io.*;
import java.net.*;

public class EchoClient
{
    public static void main(String[] args)
    {
        try
        {
            Socket s = new Socket("my static ip address here", 3000);
            BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));
            PrintWriter w = new PrintWriter(s.getOutputStream(), true);
            BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
            String line;
            do
            {
                line = r.readLine();
                if ( line != null )
                    System.out.println(line);
                line = con.readLine();
                w.println(line);
            }
            while ( !line.trim().equals("bye") );
        }
        catch (Exception err)
        {
            System.err.println(err);
        }
    }
}

When i run it(both). The client program runs and it halts without any error. It just hangs.

当我运行它(两者)。客户端程序运行并停止,没有任何错误。它只是挂起。

I appreciate your help very much!

我非常感谢你的帮助!

回答by M S Parmar

Actually when your client code try to connect to server and send "string massage" to server at this time server read inputstream (by bufferreader) i.e. line = r.readLine(); // server code

实际上,当您的客户端代码尝试连接到服务器并向服务器发送“字符串消息”时,此时服务器读取输入流(通过 bufferreader)即 line = r.readLine(); // 服务器代码

here it would wait for \n or \r or \n\r (Line Feed, Carriage Return )at the end of String.

在这里它会在字符串的末尾等待 \n 或 \r 或 \n\r (换行,回车)。

so you need to append last character as \n or \r or \n\r both side while sending massage to server or vis-versa..

所以你需要在向服务器发送消息时将最后一个字符附加为 \n 或 \r 或 \n\r 。

.
.
.
    do
                {
                    line = r.readLine();
                    line = line +"\n"; // Add this line
                    if ( line != null )
                        System.out.println(line);
                    line = con.readLine();
                    w.println(line);
                }
.
.
.

@Client code

@客户端代码