This isn't possible using an ERC20 token, it would require another function call to your smart contract to say that the tokens have been sent.
There are ERCs which try to deal with the situation you have mentioned such as ERC223 which would add a tokenFallback
function to contracts for handling token transfers. If you were dealing with ERC223 tokens then you use the tokenFallback
function to send tokens in response to tokens being received.
To implement this with ERC20 tokens you would need the person exchanging tokens to give your contract a token allowance, and then call the claimTokens
function.
(Very) Rough sample contract:
contract ExchangeTokens {
address tokenToSend;
function claimTokens(address tokenSent) {
uint256 numTokens = ERC20(tokenSent).allowance(msg.sender, this);
if (numTokens > 0) {
ERC20(tokenSent).transferFrom(msg.sender, this, numTokens);
ERC20(tokenToSend).transfer(msg.sender, numTokens);
}
}
}