【问题标题】:Java, client-server communicationJava,客户端-服务器通信
【发布时间】:2012-01-22 17:01:38
【问题描述】:

我有一个小 server.jar,它在端口 10000 上侦听 GET 和 END 命令。

我的客户代码是:

package communication;

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

public class Client {

public static void main(String args[]) throws Exception {
    try {

            Socket socket = null;
            PrintWriter out = null;
            BufferedReader in = null;

            socket = new Socket("localhost",10000);
            System.out.println("SOCKET = " + socket);
            System.out.print(socket.getInetAddress() + "\n");
            System.out.print(socket.getInputStream() + "\n");
            System.out.println(socket.isConnected() + "\n");

            out = new PrintWriter(socket.getOutputStream(),true);

            in = new BufferedReader(new 
                            InputStreamReader(socket.getInputStream()));

            String str = "GET";
            out.println(str);   
            String reponse = in.readLine();
            System.out.println(socket.isConnected() + "\n");
            for(int i = 0; i < 10; i++){
                    out.println(str);          // envoi d'un message
                    reponse = in.readLine();      // lecture de la reponse
                    System.out.println("Forme recue: " + reponse);
            }
            System.out.println("END");     // message de terminaison
            out.println("END") ;
            in.close();
            out.close();
            socket.close();

    }
    catch(IOException e) {
            System.out.println(e.getCause());
    }
}
}

我知道这段代码有效,因为它在我的一台计算机上运行。但是,我不能让它在另一个上运行。两者的配置是:Windows 7 64、JRE 6、Eclipse。

我的 server.jar 应用程序打开了一个小 GUI,让我知道通信是否打开,这在计算机上绝不会卡在 readLine() 行上。

我尝试关闭 Windows 防火墙、防病毒软件...没有任何效果。

有人知道这里出了什么问题吗?

谢谢!!

【问题讨论】:

  • 我们需要更多信息来帮助您。你得到什么错误?什么行为等等。
  • 我没有收到任何错误,程序只是卡在 String reponse = in.readLine();就我而言,实际上是缺乏让我感到困扰的行为;)
  • 你到底想测试什么?如果您想要服务器-客户端通信,为什么没有任何 SocketServer?
  • “服务器”只是一个小的可执行 jar。我启动它,然后它在端口 10000 上侦听,等待 GET 和 END 命令。我用 Telnet 对其进行了测试,工作 #1

标签: java windows eclipse socket.io


【解决方案1】:

我盯着localhost 字符串,有一种预感可能是问题所在。

在此post 的回答中,:: localhost 可能有一些需要评论的内容,并将 localhost 硬编码为 127.0.0.1在您的 C:\Windows\System32\drivers\etc\hosts 文件中。

通过使用特定 IP 地址对 localhost 进行硬编码,服务器将侦听与您的客户端程序尝试连接的 localhost 相同的localhost

【讨论】:

  • 有趣,今晚我会试试,我会及时通知你。谢谢!!
【解决方案2】:

首先要尝试 - 在 out.println 之后添加一个 out.flush()。

【讨论】:

  • 我刚刚试过了,什么都没有,仍然停留在 readLine()。而且我强烈怀疑我必须更改代码,因为它可以在另一台计算机上运行......那一定是别的......我猜:)
  • 有一件事我没有提到,System.out.println(socket.isConnected() + "\n");返回真。
  • 你是对的,你正在设置自动刷新。您确定服务器正在接收您的请求并打印响应吗?只是为了好玩,您可以尝试在每个 println 之后关闭输出流(然后在每个 println 之前打开一个新流)。
  • 在客户端,连接似乎是打开的;但是,在服务器端,即在我的 server.jar GUI 上,没有出现连接。使用 Putty-telnet,在同一个端口(10000)上,服务器的 GUI 上会弹出生命,我可以手动发送 GET 和 END 命令,并从服务器获取我想要的作为回报......
  • 你的服务器端是否使用了ServerSocket?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-05
  • 1970-01-01
  • 2015-05-08
  • 2013-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多