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

不错,还有我有一个方法,你可以试试,也许,如果它是有用的,你可以考虑为您实现。

首先,我将创建一个实体来处理这些值并将其填入传入数据。

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

}

如果你想使用字符串,让您的结构,我将简化和降低我的影响/ O通过使用String方法。既然你知道你总是期待用户/密码,我会合并你的两个参数在一个单一的字符串或使用特殊的字符和在服务器端处理StringTokenizer类。或者,也许可以用“分割”方法来处理。你在这里有很多选择。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值