那么我的问题可能看起来很愚蠢,但我需要找到答案。等待来自客户端的消息的java服务器
我想从一个android应用程序(客户端)发送一个字符串到一个java服务器,等待这样的消息从许多android客户端,并将它们存储在一个文件中。 客户端编码是好的,我写了教程和博客的帮助,那就是:
HttpURLConnection conn = null;
try {
Log.e("URL", "> " + url);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
我想要的是java中的服务器可以处理来自不同的Android应用这些消息并存储消息字符串成文本文件。我只想知道如何处理这些传入的消息并将它们变为空字符串。
到目前为止,我已经做了一些可怜的试验用下面的服务器端编码:
int port = 8080;
ServerSocket ss = new ServerSocket(port);
Socket s = ss.accept();
while(true) {
if (s == null) {
/* nothing to do */
try {
wait();
} catch (InterruptedException e) {
continue;
}
}
try {
InputStream is = new BufferedInputStream(s.getInputStream());
PrintStream ps = new PrintStream(s.getOutputStream());
ANDROID_DEVICE = ps.flush();
}catch(IOException e){}
}
如果我的问题是地方已经提出和回答,请张贴在评论的链接,我不介意你下来投票,因为我真的搜索并找不到答案。
对于那些用示例代码回答我的问题的天使,我感谢你。
我不会通过编写我自己的服务器来解决这个问题,除非您有足够的理由这么做。我希望使用基于Java的应用程序服务器(例如,tomcat),并使用诸如servlet之类的技术开发解决方案。它需要等待消息的所有痛苦 - 你只需编写代码来处理业务逻辑(在你的情况下写入一个文件)。 – DaveH
@DaveHowes我必须使用java和tomcat,而不是使用我应该写入的文件,而是使用我可以执行的Mysql数据库。而且,我有专用的服务器以供应用程序进行通信。 –