JAVA TCP 客户端-服务器连接

JAVA TCP Client-Server connection

当我 运行 这个程序时,客户端 class 提示用户输入命令,该命令应该转到服务器 class 并打开一个文件并读取每一行该文件和 return 字节长度返回给客户端 class 以显示。

不幸的是,一旦我输入命令,什么也没有发生&不知道为什么。

TCP 客户端Class

package TcpClient;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
import java.io.*;

public class TcpClient {
  public static void main(String[] args) {
    String temp;
    String displayBytes;
    try {
      //create input stream
      BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
      //create client socket, connect to server
      Socket clientSocket = new Socket("localhost",5555);
      //create output stream attached to socket
      DataOutputStream outToServer =
      new DataOutputStream(clientSocket.getOutputStream());

      System.out.print("Command : ");

      //create input stream attached to socket
      BufferedReader inFromServer =
      new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

      temp = inFromUser.readLine();

      //send line to server
      outToServer.writeBytes(temp);

      //read line from server
      //displayBytes = inFromServer.readLine();

      while((displayBytes = inFromServer.readLine()) != null) {
        System.out.print(displayBytes);
      }
      //clientSocket.close();
    }
    catch(Exception ex) {
    }
  }
}

TCP 服务器Class

package TcpServer;

import java.io.BufferedReader;
import java.io.*;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
  public static void main(String[] args) {
    // The name of the file to open.
    String fileName = "input.txt";
    // This will reference one line at a time
    String line = null;
    String holder=null;
    String clientWord;
    int bytNumber;

    try {
      //create welcoming socket at port 5555
      ServerSocket welcomeSocket = new ServerSocket(5555);
      //wait, on welcoming socket for contact by client
      Socket connectionSocket = welcomeSocket.accept();
      //create input stream, attached to socket
      BufferedReader inFromClient = 
      new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
      //create output stream, attached to socket
      DataOutputStream outToClient =
      new DataOutputStream(connectionSocket.getOutputStream());
      //read in line from socket
      clientWord = inFromClient.readLine();

      if(clientWord.equals("query")) {
        try {
          // FileReader reads text files in the default encoding.
          FileReader fileReader = new FileReader(fileName);

          // Always wrap FileReader in BufferedReader.
          BufferedReader buffer = new BufferedReader(fileReader);

          while((line = buffer.readLine()) != null) {
            System.out.println(line);
            bytNumber = line.getBytes().length;
            holder=Integer.toString(bytNumber);
            //pr.println(bytNumber);//only printing first line not going until eof
            outToClient.writeBytes(holder);
            // line = buffer.readLine();
            // pr.flush();
          }   

          // Always close files.
          buffer.close();         
        }
        catch(FileNotFoundException ex) {
          System.out.println("Unable to open file '" + fileName + "'");
        }
        catch(IOException ex) {
          System.out.println ("Error reading file '" + fileName + "'");
          // Or we could just do this: 
          // ex.printStackTrace();
        }
      }// end if statement
    }
    catch(Exception ex) {
    }
  }
}

我建议你只在两侧使用 DataOutputStreamDataInputStream,不要使用 BufferedInputStream。 下面稍微修改的代码能够正确地将消息从客户端发送到服务器。现在您可以轻松地让它为您想要实现的目标工作。

服务器

import java.io.BufferedReader;
import java.io.*;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;



public class TcpServer {


public static void main(String[] args) {
    // The name of the file to open.
    String fileName = "input.txt";
    // This will reference one line at a time
    String line = null;
    String holder=null;
    String clientWord;
    int bytNumber;

    try
    {
        //create welcoming socket at port 5555
        ServerSocket welcomeSocket = new ServerSocket(5555);
        //wait, on welcoming socket for contact by client
        Socket connectionSocket = welcomeSocket.accept();
        //create input stream, attached to socket
        DataInputStream inFromClient =
                new DataInputStream(connectionSocket.getInputStream());
        //create output stream, attached to socket
        DataOutputStream outToClient =
                new DataOutputStream(connectionSocket.getOutputStream());
        //read in line from socket
        clientWord = inFromClient.readUTF();
    System.out.println(clientWord);

        if(clientWord.equals("query"))
        {


            try 
            {
         // FileReader reads text files in the default encoding.
         FileReader fileReader = new FileReader(fileName);


         // Always wrap FileReader in BufferedReader.
         BufferedReader buffer = new BufferedReader(fileReader);


                while((line = buffer.readLine()) != null) 
                {
             System.out.println(line);
             bytNumber = line.getBytes().length;
             holder=Integer.toString(bytNumber);
             //pr.println(bytNumber);//only printing first line not going until eof
            outToClient.writeBytes(holder);
             // line = buffer.readLine();
            // pr.flush();
                }   

         // Always close files.
         buffer.close();         
            }
            catch(FileNotFoundException ex) 
            {
         System.out.println(
             "Unable to open file '" + 
             fileName + "'");                
            }
            catch(IOException ex) 
            {
         System.out.println(
             "Error reading file '" 
             + fileName + "'");                  
         // Or we could just do this: 
         // ex.printStackTrace();
            }

        }// end if statement
    }

  catch(Exception ex)
    {

    }
}

}

客户端

import java.io.BufferedReader;
  import java.io.InputStreamReader;
  import java.net.Socket;
  import java.io.*;


  public class TcpClient {


       public static void main(String[] args) {
         String temp;
         String displayBytes;
        try
        {
        //create input stream
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        //create client socket, connect to server
        Socket clientSocket = new Socket("localhost",5555);
        //create output stream attached to socket
        DataOutputStream outToServer =
                new DataOutputStream(clientSocket.getOutputStream());



        System.out.print("Command : ");

        //create input stream attached to socket
        DataInputStream inFromServer = new DataInputStream(clientSocket.getInputStream());

        temp = inFromUser.readLine();

        //send line to server
        //outToServer.writeBytes(temp);
        outToServer.writeUTF(temp);
        outToServer.flush();


       //read line from server
        //displayBytes = inFromServer.readLine();

        while((displayBytes = inFromServer.readUTF()) != null)
        {
        System.out.print(displayBytes);
        }
        //clientSocket.close();
    }
    catch(Exception ex)
    {

    }
}
}