- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我创建了两个 android 应用程序,一个客户端和一个服务器,利用 TCP 进行跨设备通信。在服务器上,我有这段代码来监听 TCP 通信:
private class StartServer implements Runnable {
public void run() {
getState(); // This just refreshes the server state
try {
serverSocket = new ServerSocket(5000);
appendLog("Server successfully listening ["+getLocalIpAddress() + ":5000]"); //appendLog function just uses runOnUiThread() to update the log textview
} catch (IOException e) {
appendLog("Could not listen on port: 5000");
//System.exit(-1);
}
BufferedReader in = null;
BufferedWriter out = null;
String input = null;
try {
clientSocket = serverSocket.accept();
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
while (serverState) { //variable set by our getState() function
input = in.readLine();
appendLog("Received: " + input);
this.gotMessage(out, input);
}
in.close();
out.close();
} catch (IOException e) {
//appendLog(e.toString());
appendLog("Accept failed: 5000");
//System.exit(-1);
}
}
调用此函数来实际解析收到的消息:
private void gotMessage(BufferedWriter output, String msg) {
if (msg != null) {
String sString = msg;
int to_do = 0;
if (msg.matches("^(?i)(exit|quit|close)$")) {
appendLog("Exiting");
sString = "Goodbye";
to_do=1;
} else if (msg.matches("^(?i)(launch|run|open)\\s(.+)")) {
appendLog("Launching application");
sString = "Launching application";
} else if (msg.matches("^(?i)(turn off|server off|deactivate)$")) {
appendLog("Turning off server due to remote command.");
sString = "Turning off...";
to_do=2;
} else if (msg.matches("^(?i)(restart|reboot)$")) {
appendLog("Resetting server");
sString = "Rebooting now...";
to_do=3;
}
try {
output.write("S: " + sString);
output.newLine();
output.flush();
} catch (IOException e) {
appendLog("Cannot parse message");
}
switch(to_do) {
case 0:
break;
case 1:
System.exit(0);
break;
case 2:
serverOff();
break;
case 3:
serverOff();
serverOn();
break;
default:
break;
}
}
}
}
服务器线程本身使用 Thread t = new Thread(new StartServer()); 启动; t.start()
。据我所知,这很好用。我可以打开一个终端并远程登录到 IP 和端口,并且可以毫无错误地来回传递通信。但是当我尝试从下面的客户端代码做同样的事情时。我只收到第一条消息,我传入的任何其他消息都会消失在空白中。
public void sendToServer(View v) {
try {
String ip = ((TextView)findViewById(R.id.ip_box)).getText().toString(); //User entered IP address
String to_send = ((EditText)findViewById(R.id.send_to_server)).getText().toString(); //User entered text to send
this.s = new Socket(ip, 5000);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
appendLog("Sending: " + to_send);
out.write(to_send);
out.newLine();
out.close();
} catch (Exception e) {
Log.d("error", e.toString());
}
}
最佳答案
to_send
字符串中是否有行尾字符?如果不是,只需将 out.newLine()
添加到您的客户端代码中:
appendLog("Sending: " + to_send);
out.write(to_send);
out.newLine();
你的服务器代码应该像这样支持多个客户端:
// main server loop
while (serverIsActive) {
clientSocket = serverSocket.accept();
// spawn new thread for each client
ClientThread ct = new ClientThread(clientSocket);
ct.start();
}
ClientThread 应该与客户端套接字一起工作,并有自己的读取行的循环。它应该在客户端关闭套接字后立即停止:
class ClientThread {
...
public void run() {
....
while ((inputLine = in.readLine()) != null) {
// process client message
}
in.close();
}
}
关于java - Android TCP 客户端/服务器未正确传递消息(仅首次收到),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16611745/
我有一个静态类。 static class AppDirectory { public static string PACSTEMP = Path.Combine(Path.GetTempPa
我已经设置了一个启用了推送通知的 iOS 应用。 我可以将消息推送到应用程序,例如角标(Badge)计数工作并相应更新。 但我从未在锁屏或其他地方看到标准的推送通知弹出窗口,但手机会振动,因此消息会通
我们有一个带有 Web 应用程序和一堆 Windows 服务的系统,它们在做一些后台工作。 每当我们需要对系统进行更实质性的更改时,我们最终不得不发出 IIS 重置,然后手动重新启动所有相关的 Win
我有以下几行 John SMith: A Pedro Smith: B Jonathan B: A John B: B Luis Diaz: A Scarlet Diaz: B 我需要获得所有获得
我正在编写一个 Java 客户端(在 weblogic 10.3 上)来调用一个安全的网络服务。我已获得安装在 cacerts、DemoIdentity.jks 和 DemoTrust,jks 中的客
已关闭。此问题不符合Stack Overflow guidelines 。目前不接受答案。 这个问题似乎偏离主题,因为它缺乏足够的信息来诊断问题。 更详细地描述您的问题或 include a mini
我正在尝试调用void方法addToList,该方法将通过用户传递给它的两个字符串除外。我检查了dataSource类,以确保它确实接受了那些作为参数。问题是我在该方法调用上始终收到标识符>预期错误,
我的任务:使用scanner方法从一行数据中提取字符串、 float 和整数。 数据格式为: Random String, 240.5 51603 Another String, 41.6 59087
这个问题已经有答案了: What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? (25 个回答)
首先我实例化一个游戏状态 class GameState extends state{ ArrayList levels; int currentLevelID; public GameState()
已关闭。这个问题是 not reproducible or was caused by typos 。目前不接受答案。 这个问题是由拼写错误或无法再重现的问题引起的。虽然类似的问题可能是 on-top
我有一个实现为单例的 Controller 对象,它有一个可以随时驱逐对象的缓存。当一个对象即将被删除时,我想通知任何使用此 Controller 的类,以便它们能够做出适当的响应。我对这种行为的第一
因此,我尝试跨集群发送消息,该消息将包含一个 User 对象,该对象是一个可序列化类。 当我发送 String 或 int 时,它工作正常,消息发送没有问题,并且集群上的所有 channel 都收到它
我试图创建的程序是一个基本游戏,用户输入网格大小,选择 block 接收增加分数的奖品、从分数中夺走分数的强盗或结束游戏的炸弹。我收到堆栈流错误,但我不明白为什么? 抱歉,代码量很大,我只是无法找到问
使用此代码我会得到什么ConcurrentModificationException?我有一个同步(监听器)锁。 private void notifyListeners(MediumRenditio
我想在捕获 DeadlineExceededError 后正确退出。我还剩下多少钱来清理? 例如, try: do_some_work() except DeadlineExceededError
我有 2 个 Intranet 站点: http://intranetv1/ http://intranetv2/ v1基于.NET 1.1,v2基于.NET 3.5 在 v1 上,我创建了一个网页,
我有一个在 Linux 3.12 上运行的 C 程序。该程序产生几个子进程。其中一个进程会生成一个线程,该线程运行一段时间然后终止。当该子进程运行时,它会执行 epoll_wait()。 epoll_
我能够将 APNS 集成到我的应用程序中。现在我想在用户点击它或用户在使用应用程序时收到通知时处理通知。我使用下面的代码在收到通知时显示警报对话框: func application(applicat
当我试图在浏览器上运行这段代码时,出现了以下错误。"错误响应错误代码:501消息:不支持的方法(“POST”)。错误码解释:501-服务器不支持该操作。" 浏览器控制台出现以下错误: "1.加载资源失
我是一名优秀的程序员,十分优秀!