有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从客户端发送到服务器的Java消息

我正在使用socket将我的客户机与服务器连接,我需要一种方法,以便当有人尝试使用帐户登录客户机时,它将用户名和密码发送到服务器,并检查帐户是否存在。我只需要知道如何使它发送消息到服务器时,他们按登录

我试图让它向服务器发送消息

public static void sendmsg(String a, String b)
    {
        try
        {
            String host = "127.0.0.1";
            int port = 43655;
            InetAddress address = InetAddress.getByName(host);
            socket = new Socket(address, port);

            //Send the message to the server
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);


            String sendMessage = a;
            bw.write(sendMessage);
            bw.flush();
            System.out.println("Message sent to the server : "+sendMessage);

            //Get the return message from the server
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String message = br.readLine();
            System.out.println("Message received from the server : " +message);
        }
        catch (Exception exception) 
        {
            exception.printStackTrace();
        }
        finally
        {
            //Closing the socket
            try
            {
                socket.close();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }

共 (2) 个答案

  1. # 1 楼答案

    不错,你正在使用套接字,我有一个方法可以尝试,如果有用的话,你可以考虑你的实现。

    首先,我将创建一个实体来处理这些值,并用传入的数据填充它

    class UserAuth {
        private String username;
        private String password;
        //Consider here your getters and setters, I am not including them       
    }
    

    我将在发送时使用实体作为方法的参数,也许您可以将其填充为如下内容:

    UserAuth attemptingUser = new UserAuth(...)
    

    ObjectInputStream适用于此类场景。如果仍然想使用字符串,可以使用BufferedReader,尝试将用户名和密码合并为一个字符串,然后使用。readLine()方法来获取(用逗号分隔),然后使用String方法,比如Split,但我发现这可能需要更多时间,如果用对象来处理,应该会更好。但这取决于要添加到应用程序中的复杂性:)

    class AuthClient {
    
        public void sendMsg(UserAuth attemptingUser) {
            String host =  "localhost";
            int port = 2055;
            //1. Create the socket
            Socket sender = new Socket(host, port);
            //2. Create an object output stream to write the object into the stream
            ObjectOutputStream outputWriter = new ObjectOutputStream(sender.getOutputStream());
            //3. Write (send the object)
            outputWriter.writeObject(attemptingUser);
            //4. Close
            outputWriter.close();
            sender.close();
        }
    }
    
    class AuthServer {
    
        ServerSocket ss = new ServerSocket(2055);
    
        public void receiveMsg() {
            //1. Accept the connection
            Socket conn = ss.accept();
            //2. Receive the flow
            ObjectInputStream readStream = new ObjectInputStream(conn.getInputStream());
            //3. Read the object
            UserAuth userReceived = readStream.readObject();
            //4. Verify against file, db or whatever
            if (userReceived.getUsername().equals("admin") && userReceived.getPassword().equals("admin")) {
                //Authentication
            }
        }
    
    }
    

    (这是我为你在评论中问我的问题编辑的部分)

    public void sendMsg(String username, String password) {
                String host =  "localhost";
                int port = 2055;
                //1. Create the socket
                Socket sender = new Socket(host, port);
                //2. Create the UserAuth object based on the parameters you received
                UserAuth myuser = new UserAuth();
                myuser.setUsername(username);
                myuser.setPassword(password);
                //3. Follow same instructions for the creation of ObjectOutputStream...
                ObjectOutputStream objectWriter = new ObjectOutputStream(sender.getOutputStream());
                objectWriter.writeObject(myuser);
                //That is what I would use if I keep your structure
            }
    

    如果希望使用字符串保持结构,我将通过使用字符串方法简化并减少I/O的影响。因为您知道您总是需要用户/密码,所以我会将您的两个参数合并到一个字符串中,或者使用特殊的char和服务器端句柄来处理StringTokenizer类。或者用“拆分”的方法处理。你有很多选择

    到目前为止,这将是我解决你们面临的问题的方法。希望能有所帮助。致以最诚挚的问候,祝您愉快:)

  2. # 2 楼答案

    在我看来,您所做的一切都很好,但这完全取决于服务器希望接收到什么。终止字符是什么,除非它已经包含在String a变量中,否则您没有发送终止字符

    如果服务器需要一个行尾字符(您当前没有发送),可以使用PrintWriter而不是像这样的BufferedWriter

    pw = new PrintWriter(socket.getOutputStream(), true);
    pw.println(a);
    

    你的服务器就会这样做

    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String value = br.readLine();