无法使用Java将数据从服务器发送到客户端仅反之 [英] Cant send data from Server to client only viceverse using java

查看:133
本文介绍了无法使用Java将数据从服务器发送到客户端仅反之的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图解决这个问题大约5个小时,但似乎看不到它,尽管所有步骤均已完成发送数据的操作,但我只能接收到服务器的消息,而不能接收服务器到客户端的消息.我正处于构建/学习如何在命令行中执行聊天客户端程序的早期阶段.以下是服务器代码:

been trying to figure this problem out for about 5 hours but cant seem to see it, although all the steps are done to send data, I can only receive messages to the server, but not from server to client. I'm in the early stages of building/learning how to do a chat client program in command line. The following is the server code:

CServer类:

public class CServer {

private static int port=2008, maxConnections=0;
private static String shutDownServer = "no";

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


    ServerSocket listen = new ServerSocket(port);
    Socket server;

    while(shutDownServer.equalsIgnoreCase("no")){

        doComm connection;

        System.out.println("\nWaiting for clients to connect...");

        server = listen.accept(); // accept incomming connections from client
        System.out.println("Client connected. Location: " + server.getInetAddress().getHostName());
        connection = new doComm(server);

        Thread thread = new Thread(connection);
        thread.start();
    }



}

public void shutDownServer(String command){

    this.shutDownServer = command;
}
}

现在处理线程中每个客户端的doComm类:

Now the doComm class that handles each client in thread:

public class doComm implements Runnable{

Socket server;
private String clientData;

  public doComm(Socket server){

      this.server = server;
  } 

  public void run(){

     try {

      BufferedReader fromClient = new BufferedReader(new InputStreamReader(server.getInputStream()));
      DataOutputStream toClient = new DataOutputStream(server.getOutputStream());

      clientData = fromClient.readLine();
         System.out.println("Client sent: "+clientData);

((问题-imo-可能是以下语句:))

(( The problem -imo- may be either this statement: ))

      toClient.writeBytes("Recieved your sentence '"+clientData+"' and more to come :)!");

    //server.close();

  } catch (IOException e) {
    System.out.println("IOException on socket listen: " + e);
    e.printStackTrace();
  }

  }
}

现在,客户端类CClient:

Now the client class CClient:

    public class CClient {

    static String address = "localhost";

static int port = 4444;
static Socket echoSocket;

     public CClient(int port, String addr){

         changePort(port);
         changeAddr(addr);
     }

     public static void main(String[] args) throws IOException, UnknownHostException{

         Scanner scan = new Scanner(System.in);

         System.out.println("Please enter the port to connect to: ");
         int temp_port = Integer.parseInt(scan.nextLine());
         System.out.println("Please enter the address of server: ");
         System.out.flush();
         String temp_addr = scan.nextLine();

         CClient client = new CClient(temp_port,temp_addr);

            PrintWriter out = null;
            BufferedReader in = null;

         try{
             System.out.flush();
             echoSocket =  new Socket(address,port);
             out = new PrintWriter(echoSocket.getOutputStream(), true);
             in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
         }
         catch(IOException e){

             System.err.println("IOException error: " + e.getStackTrace());
         }

         BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
    String userInput;

    while ((userInput = stdIn.readLine()) != null) {

        out.println(userInput);
            System.out.println("thingy prints right after this...");

(((或这里:))

System.out.println("echo: " + in.readLine());
}
 }

 public void changePort(int port){

     this.port=port;
 }

 public void changeAddr(String addr){

     this.address=addr;
 }
}

推荐答案

  clientData = fromClient.readLine();

  toClient.writeBytes("Recieved your sentence '"+clientData+"' and more to come :)!");

这是一个非常常见的问题,其根本原因是 document specify 用于通信的协议失败.在这里,您收到的是,但发送的是 bytes .如果您有协议文档,它将指定交换行或交换字节的任意单位.这表明这些代码行之一是错误的,您可以对其进行修复.但是如果没有协议规范,您甚至无法分辨哪一方是错误的.

This is a very common problem whose root cause is the failure to document and specify the protocol being used for communication. Here you are receiving lines but sending bytes. If you had a protocol document, it would either specify that lines were exchanged or that arbitrary units of bytes were exchanged. That would show that one of these lines of code is wrong, and you could fix it. But without a protocol specification, you can't even tell which side is wrong.

请从多年的痛苦教训中汲取我的建议-在实施之前记录协议.然后,如果它不起作用,则可以按照以下三个步骤进行操作:

Please, take my advice from years of painful lessons -- document a protocol before you implement. Then, if it doesn't work, you can follow this three step process:

  1. 客户端是否遵循记录的协议?如果没有,那么它就坏了.

  1. Does the client follow the documented protocol? If not, it is broken.

服务器是否遵循记录的协议?如果没有,那么它就坏了.

Does the server follow the documented protocol? If not, it is broken.

协议规范已损坏.

在这种情况下,协议规范将记录什么构成协议的消息".这样,发送完整的消息并在接收时找到这些消息边界将是双方的责任.但是,在您的情况下,一段代码需要一个行终止符来标记消息边界,而另一端则不发送消息.

In this case, the protocol specification would document what constitutes a "message" for your protocol. It would then be each side's responsibility to send complete messages and find these message boundaries on receive. However, in your case, one piece of code expects a line terminator to mark a message boundary and the other side doesn't send one.

发件人是否忽略了消息边界?接收者坚持接收一个人是错误的吗?没有人知道,因为没有规范说明做什么是正确的.

Is the sender wrong to omit a message boundary? Is the receiver wrong to insist on receiving one? Nobody knows because there's no specification to say what's the right thing to do.

这篇关于无法使用Java将数据从服务器发送到客户端仅反之的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆