如何从服务器端接收客户端的输入?

时间:2018-02-26 18:43:46

标签: java sockets tcp io client-server

如何将客户端控制台上的输入发送到服务器?到目前为止我已经

         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

            String input = br.readLine();

如何在服务器端获得“输入”?我必须在clientSocket上调用什么?我试过这个:

PrintWriter out = new PrintWriter(clientSocket.getOutputStream());

out.write(input);

在服务器端:

    serverSocket = new ServerSocket(port);
    while(true) {
        clientSocket = serverSocket.accept();
        out = new PrintWriter(clientSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

        String input = in.readLine();
        if (input.equals("2")) {
            System.out.println("activate receiveFile");
            receiveFile();
        }

然而,当我输入2时,'input'肯定不是'2'。

1 个答案:

答案 0 :(得分:0)

服务器端构造函数

 try {
  is = new BufferedReader(new InputStreamReader(new BufferedInputStream(soc.getInputStream())));
  os = new PrintWriter(new BufferedOutputStream(soc.getOutputStream()), false);
  printWriterQueue = new PrintWriterQueue(this, os, is, timeout);
  soc.setSoTimeout(5000);
  start();
} catch (Exception e){
  e.printStackTrace();
}

你应该在运行中使用一个线程

 while (!end) {
    do {
      try {
        st=is.readLine();
      } catch (InterruptedIOException ie) {
        st="";
      }
    } while (!end && st.length()==0);

客户端构造器

soc     = new Socket(IpAddress, 2999);
    in      = new BufferedReader(new InputStreamReader(soc.getInputStream()));
    out     = new PrintWriter(soc.getOutputStream());
    addText("Connection up and running...");
    soc.setSoTimeout(5000);
    printWriterQueue = new PrintWriterQueue(this, out, in, 10000);
    Thread th=new Thread(this);
    th.start();

客户端的一个线程在run()

中也是如此
try {
  do {
    do {
      try {
        msg=in.readLine();
      } catch (InterruptedIOException ie) {
        msg="";
      }
    } while (!end && msg.length()==0);
    if (!end) {
      System.out.println("["+msg+"]");
    }
  } while (!end);
} catch (Exception exc) {
  exc.printStackTrace();
}