Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java TCP服务器,客户端未从服务器接收消息_Java_Tcp - Fatal编程技术网

Java TCP服务器,客户端未从服务器接收消息

Java TCP服务器,客户端未从服务器接收消息,java,tcp,Java,Tcp,因此,我有一个java TCP服务器和客户端。客户端正在尝试向服务器注册一个用户。我可以从打印语句中看到该用户正在服务器上添加,但我的客户端没有收到“用户已添加,请尝试登录”消息 服务器 class Server implements Runnable { Socket connectionSocket; UserRepo userRepo; public static final String COMMAND_SEPARATOR = "%%"; public Server(S

因此,我有一个java TCP服务器和客户端。客户端正在尝试向服务器注册一个用户。我可以从打印语句中看到该用户正在服务器上添加,但我的客户端没有收到“用户已添加,请尝试登录”消息

服务器

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");
                }
   }

 }
import java.io.IOException;
导入java.io.PrintWriter;
导入java.net.Socket;
导入java.util.Scanner;
导入java.util.logging.Level;
导入java.util.logging.Logger;
公共类ClientShell{
公共静态最终字符串命令_SEPARATOR=“%%”;
/**
*@param指定命令行参数
*/
公共静态void main(字符串[]args){
试一试{
用户loggedInUser=null;
字符串消息=”;
字符串响应=null;
扫描仪键盘=新扫描仪(System.in);
//1)构建供客户端使用的数据套接字
套接字服务器链接=新套接字(“本地主机”,5555);
//2)设置流
//用于发送消息的PrintWriter
PrintWriter输出=新的PrintWriter(serverLink.getOutputStream());
//用于接收消息的扫描仪/缓冲读取器
扫描仪输入=新扫描仪(serverLink.getInputStream());
//3)虽然我们仍希望交换消息
而(!message.equalsIgnoreCase(“退出”))
{
while(loggedInUser==null){
notLoggedInOptions(键盘、消息、响应、loggedInUser、输出、输入);
}
}
//8)关闭与服务器的链接(数据套接字)
serverLink.close();
}捕获(IOEX异常){
Logger.getLogger(ClientShell.class.getName()).log(Level.SEVERE,null,ex);
}
}
公共静态void notLoggedInOptions(扫描仪键盘、字符串消息、字符串响应、用户loggedInUser、,
打印机输出、扫描仪输入){
System.out.println(“键入login用于登录或register用于注册”);
message=keyboard.nextLine();
if(message.equalsIgnoreCase(“登录”)){
}else if(message.equalsIgnoreCase(“寄存器”)){
message=“”;
布尔值validUserName=false;
while(validUserName==false){
System.out.println(“键入您希望作为电子邮件前缀的用户名”);
System.out.println(“必须介于5到10个字符之间”);
System.out.println(“例如,如果需要,键入mgrahammgraham@danielhaughton@豪顿网),;
message=keyboard.nextLine();
if(message.length()>4&&message.length()7){
validPassword=true;
}否则{
System.out.println(“必须至少有8个字符,请重试”);
}
}
字符串密码=消息;
System.out.println(“用户名:”+用户名);
System.out.println(“密码:”+密码);
output.println(“寄存器”+命令分隔符+用户名+命令分隔符+密码);
output.flush();
response=input.nextLine();
System.out.println(响应);
}否则{
System.out.println(“不支持的命令!重试”);
}
}
}
`

我在客户机上的输出

键入login进行登录,或键入register进行注册

登记册

键入要作为电子邮件前缀的用户名

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

如果你想的话,请键入mgrahammgraham@danielhaughton@豪顿网

丹尼尔

键入所需的密码

它必须至少是8个字符

你好12345

用户名:丹尼尔

密码:hello12345

此处打印空行


键入login进行登录或register进行注册好了,看看您的服务器返回了什么:

writer.write("\r\n=== User was added,try logging in");
因此,它发送一个空行,后跟
==用户已添加,请尝试登录。因此,由于客户端读取下一行,而接收到的下一行是空行,因此输出是您应该期望的

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

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

你在读台词,但你没有发送台词。在每个发送的消息中都需要一个行终止符

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