服务器 - 客户端Java

时间:2016-05-03 14:25:04

标签: java network-programming

我用Java创建了一个基本的服务器和客户端程序,当你启动服务器而不是客户端时,如果用户键入密码“root”并且我将该值保存为密码,那么它将连接两者,我正在尝试当它在服务器端开始连接时它输出“密码是”而不是密码的值,但每次运行它时程序输出“密码为空”,为什么它给我这个?我将字符串更改为静态,它仍然给我null,请帮助并解释??

服务器端代码

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


public void lookForConnection(){
    Socket connection;
    clientMethod cM = new clientMethod();
    {
        try
        {
            System.out.print("Program running...");
            ServerSocket serverSocket = new ServerSocket(6789);
            while(true) 
            {
                connection = serverSocket.accept();
                System.out.println("Connected Succesfully!");
                System.out.println(connection.getInetAddress().getHostName());
                System.out.println("The password for this connection is " + cM.password);              
            }
        }
        catch(IOException ex)
        {
            System.out.println (ex.toString());

        }

    }
}

客户端代码

import java.io.EOFException;
import java.util.Scanner;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class clientMethod {
    public String serverIP;
    public String password;
    public Socket connection; 
    public void Client(String host)
    {
        serverIP = host;
    }
    public void startRunning() {
        try{
            Scanner console = new Scanner(System.in);
            System.out.print("Please provide the admin password: ");
            password = console.next();
            if(password.compareTo("root") == 0 ) {
                connectToServer();          
            //}
            }
        }
        catch(EOFException eofException){
            System.out.print("\n Client terminated the connection");
        }
        catch(IOException ioException) {
            ioException.printStackTrace();
        }
    }
    private void connectToServer() throws IOException {
        System.out.println("Attempting connection...");
        connection = new Socket(InetAddress.getByName(serverIP), 6789);
        System.out.println("Connected to " + connection.getInetAddress().getHostName());

    }
}

1 个答案:

答案 0 :(得分:1)

可能是因为您从未将密码发送到服务器,因此您只打印未设置的本地变量password的变量cM的值,因此确保null

检查this tutorial以查看如何将数据发送到服务器,但基本上我们的想法是使用OutputStream中的Socket#getOutputStream()从客户端写入数据,它会发送数据到服务器以及从Socket#getInputStream()读取的服务器。