从客户端发送到服务器的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();
}
}
}
# 1 楼答案
不错,你正在使用套接字,我有一个方法可以尝试,如果有用的话,你可以考虑你的实现。
首先,我将创建一个实体来处理这些值,并用传入的数据填充它
我将在发送时使用实体作为方法的参数,也许您可以将其填充为如下内容:
ObjectInputStream适用于此类场景。如果仍然想使用字符串,可以使用BufferedReader,尝试将用户名和密码合并为一个字符串,然后使用。readLine()方法来获取(用逗号分隔),然后使用String方法,比如Split,但我发现这可能需要更多时间,如果用对象来处理,应该会更好。但这取决于要添加到应用程序中的复杂性:)
(这是我为你在评论中问我的问题编辑的部分)
如果希望使用字符串保持结构,我将通过使用字符串方法简化并减少I/O的影响。因为您知道您总是需要用户/密码,所以我会将您的两个参数合并到一个字符串中,或者使用特殊的char和服务器端句柄来处理
StringTokenizer
类。或者用“拆分”的方法处理。你有很多选择到目前为止,这将是我解决你们面临的问题的方法。希望能有所帮助。致以最诚挚的问候,祝您愉快:)
# 2 楼答案
在我看来,您所做的一切都很好,但这完全取决于服务器希望接收到什么。终止字符是什么,除非它已经包含在
String a
变量中,否则您没有发送终止字符如果服务器需要一个行尾字符(您当前没有发送),可以使用
PrintWriter
而不是像这样的BufferedWriter
你的服务器就会这样做