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

时间:2014-10-09 21:01:16

标签: java

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

我试过这个让它向服务器发送消息

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 个答案:

答案 0 :(得分: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适用于这些场景。如果你仍然想使用Strings,你可以使用BufferedReader并尝试将你的用户名和密码合并为一个单独的String并使用.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
        }

如果你想使用字符串来保持你的结构,我会通过使用String方法简化和减少I / O的影响。既然你知道你总是期望用户/密码,我会将你的两个参数合并在一个字符串中,或​​者使用特殊字符和服务器端句柄与StringTokenizer类。或者也许处理"拆分"方法。你有很多选择。

到目前为止,这将是我面对您遇到的问题的方法。希望它能以某种方式帮助。最好的问候和快乐的编码:)。

答案 1 :(得分:0)

你所做的对我来说看起来不错,但这完全取决于服务器期望收到的内容。什么是终止字符,因为除非已经包含在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();