refactor protocol handling, fix #332