TCP服务器,客户端未收到来自服务器的消息

时间:2018-04-01 09:24:55

标签: java tcp

所以我有一个java TCP服务器和客户端。客户端正在尝试将用户注册到服务器。我可以看到用户是从我的print语句添加到服务器上但我的客户端没有收到&# 34;添加了用户,尝试登录"消息。

服务器

class Server implements Runnable
{
Socket connectionSocket;
    UserRepo userRepo;
    public static final String COMMAND_SEPARATOR = "%%";

public Server(Socket s){
    try{
        System.out.println("Client Got Connected  " );
        connectionSocket=s;
                    userRepo = new UserRepo();
    }catch(Exception e){e.printStackTrace();}
}

public void run(){
    try{

               String recievedMessage="";
            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            BufferedWriter writer= 
                    new BufferedWriter(new OutputStreamWriter(connectionSocket.getOutputStream()));

                    while(!recievedMessage.equalsIgnoreCase("exit")){
            recievedMessage = reader.readLine().trim();
                    String [] components = recievedMessage.split(COMMAND_SEPARATOR);
                    if(components[0].equals("register")){
                        User user= userRepo.addUser(components[1], components[2]);
                        if(user==null){
                            writer.write("\r\n=== User wasnt added,"
                                    + "mayby there is already an account for that email? " );
            writer.flush();
                        }else{
                                writer.write("\r\n=== User was added,try logging in");
                                System.out.println("user added");
            writer.flush();
                        }
                    }


            recievedMessage="";
                    recievedMessage = reader.readLine().trim();
                    }
            connectionSocket.close();
    }catch(Exception e){e.printStackTrace();}
}

 public static void main(String argv[]) throws Exception
  {
     System.out.println("Threaded Server is Running  " );
     ServerSocket mysocket = new ServerSocket(5555);
     while(true)
     {
        Socket sock = mysocket.accept();
        Server server=new Server(sock);

        Thread serverThread=new Thread(server);
        serverThread.start();

     }
  }
 }

客户端

    import java.io.IOException;
     import java.io.PrintWriter;
   import java.net.Socket;
  import java.util.Scanner;
 import java.util.logging.Level;
 import java.util.logging.Logger;


     public class ClientShell {
   public static final String COMMAND_SEPARATOR = "%%";
/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    try {
        User loggedInUser = null;
        String message = "";
        String response = null;
        Scanner keyboard = new Scanner(System.in);

        // 1) Build data socket for client to use
        Socket serverLink = new Socket("localhost", 5555);

        // 2) Set up streams
        // PrintWriter used for sending messages
        PrintWriter output = new PrintWriter(serverLink.getOutputStream());
        // Scanner / BufferedReader used for receiving messages
        Scanner input = new Scanner(serverLink.getInputStream());

        // 3) While we want still want to exchange messages
        while(!message.equalsIgnoreCase("exit"))
        {
            while(loggedInUser==null){
                notLoggedInOptions(keyboard,message,response,loggedInUser,output,input);
            }


        }
        // 8) Close the link to the server (the data socket)
        serverLink.close();
    } catch (IOException ex) {
        Logger.getLogger(ClientShell.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public static void notLoggedInOptions(Scanner keyboard,String message,String response,User loggedInUser,
                                PrintWriter output,Scanner input){
    System.out.println("Type login for login or register for register");
                message = keyboard.nextLine();
                if(message.equalsIgnoreCase("login")){

                }else if(message.equalsIgnoreCase("register")){
                    message="";
                    boolean validUserName = false;
                    while(validUserName == false){
                    System.out.println("Type the username you want as your prefix for your email");
                    System.out.println("It must be between 5 and 10 characters");
                    System.out.println("eg type mgraham if you want mgraham@danielhaughton@haughton.com");
                    message = keyboard.nextLine();
                    if(message.length()>4 && message.length()<11 == true){
                        validUserName = true;
                    }else{
                        System.out.println("It must be between 5 and 10 characters try again" );
                    }
                    }
                    String username = message;
                    message="";
                    boolean validPassword = false;
                    while(validPassword == false){
                        System.out.println("Type the password you want");
                    System.out.println("It must be atleast 8 characterrs");
                    message = keyboard.nextLine();
                    if(message.length()> 7){
                        validPassword = true;
                    }else{
                        System.out.println("It must be atleast 8 characterrs,try again");
                    }
                    }
                    String password = message;
                    System.out.println("username:" + username);
                    System.out.println("password:" + password);
                    output.println("register"+ COMMAND_SEPARATOR + username + COMMAND_SEPARATOR + password);
                    output.flush();
                    response = input.nextLine();
                    System.out.println(response);
                }else{
                    System.out.println("Unsupported command!try again");
                }
   }

 }

`

我在客户端上的输出

输入登录登录或注册登记

寄存器

输入您想要的用户名作为电子邮件的前缀

必须介于5到10个字符之间

例如,如果你想要mgraham @ danielhaughton @ haughton.com

,请输入mgraham

丹尼尔

输入您想要的密码

必须至少8个字符

hello12345

用户名:丹尼尔

密码:hello12345

此处打印空行

输入登录登录或注册登记

2 个答案:

答案 0 :(得分:0)

好吧,看看你的服务器发回的内容:

writer.write("\r\n=== User was added,try logging in");

因此,它会发送一个空行,然后是=== User was added,try logging in。因此,由于客户端读取下一行,并且接收到的下一行是空行,因此输出是您应该期望的。

如果您希望打印消息,则服务器应使用

writer.write("=== User was added,try logging in\r\n");

答案 1 :(得分:0)

您正在阅读线路,但您没有发送线路。每个发送的消息都需要一个行终止符。

注意:在执行任何其他代码之前,您必须检查readLine()的结果是否为空。