情况:Android手机已通过USB连接到PC。使用ADB命令adb forward tcp:35000 tcp:30000
,我成功转发了一个端口
我希望PC每隔5秒将其系统时间发送到Android手机一小时。为此,我进行了套接字编程。
PC端作为客户端:(我忽略了异常处理代码。)
public void sendTime()
{
class SendTask implements Runnable
{
public void run()
{
// Here: I store the host_socket in a member field which is:
// Socket host_socket = new Socket("localhost", 35000);
ObjectOutputStream oos = new ObjectOutputStream(this.host_socket.getOutputStream());
oos.writeObject(msg);
oos.flush();
}
}
// Here: private Executor exec = Executors.newCachedThreadPool();
this.exec.execute(new SendTask());
}
Android手机端作为服务器:
public void getReadyForSync()
{
ServerSocket server_socket = new ServerSocket();
server_socket.bind(new InetSocketAddress("localhost", 30000));
while (true)
{
final Socket client_socket = server_socket.accept();
Runnable receive_task = new Runnable()
{
public void run()
{
ObjectInputStream ois = new ObjectInputStream(client_socket.getInputStream());
Message msg = (Message) ois.readObject();
SyncTimeFragment.this.onReceive(msg);
}
};
// Here: private static final Executor exec = Executors.newCachedThreadPool();
exec.execute(receive_task);
}
}
此外,ServerSocket是使用AsyncTask
和new ServerTask().execute()
在主Android线程的单独线程中建立的:
public class ServerTask extends AsyncTask<String, Void, Void>
{
protected Void doInBackground(String... params)
{
getReadyForSync();
return null;
}
}
问题:
在我的测试中,Android手机中的服务器套接字仅接受来自PC 的连接。
具体来说,一些调试信息如下:
(1)每次(每5秒钟)sendTime()
被调用,host_socket
读取:
Socket[addr=localhost/127.0.0.1,port=35000,localport=56520]
注意:此处localport
(s)对于单次执行中的所有sendTime()
次调用都是相同的,但执行次数不同。 (我不确定这些信息是否重要。)
(2)server_socket
读取:
Socket[addr=localhost/127.0.0.1,port=0,localport=30000]
(3)client_socket
收到的server_socket
(仅一次)读取:
Socket[addr=/127.0.0.1,port=43890,localport=30000]
答案 0 :(得分:2)
创建receive_task
后代码返回final Socket client_socket = server_socket.accept();
因此服务器会抛弃连接,因为run()
只会抓取一条消息。您也必须在while
中进行run()
循环。