@Override
public void run() {
tcpConnections = new ArrayList<>();
try {
ss = new ServerSocket(port);
Log.d("Listening","Listening on port : " + ss.getLocalPort());
while (true) {
Log.d("Listening","Waiting for Client");
socket = ss.accept();
if (socket.isConnected())
{
Log.d("SocketAccept", "client connected from: %s" + socket.getRemoteSocketAddress().toString());
TCPConnection tcpConnection = new TCPConnection(socket); // is it right way to start further steps of listening for incoming connections?
tcpConnections.add(tcpConnection);
tcpConnection.run();
}
else {
StopConnections();
break;
}
}
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (IOException e) {
Log.d("Socket","socket is closed");
}
}
监听连接,它接受一个连接,如果接受成功, 该连接将添加到tcpConnections列表中,并运行TCPConnection进行进一步侦听。 能否请有人告诉我知道可以使用AsyncTask放置所有内容?
这就是我从MainActivity拨打电话的方式
btn_Conn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
TCPServer connection = new TCPServer(7123);
new Thread(connection).start();