定义
org.apache.tomcat.websocket.WsRemoteEndpointImplBase.StateMachine
private static enum State {
OPEN,
STREAM_WRITING,
WRITER_WRITING,
BINARY_PARTIAL_WRITING,
BINARY_PARTIAL_READY,
BINARY_FULL_WRITING,
TEXT_PARTIAL_WRITING,
TEXT_PARTIAL_READY,
TEXT_FULL_WRITING
}
private static class StateMachine {
private State state = State.OPEN;
public synchronized void streamStart() {
checkState(State.OPEN);
state = State.STREAM_WRITING;
}
public synchronized void writeStart() {
checkState(State.OPEN);
state = State.WRITER_WRITING;
}
public synchronized void binaryPartialStart() {
checkState(State.OPEN, State.BINARY_PARTIAL_READY);
state = State.BINARY_PARTIAL_WRITING;
}
public synchronized void binaryStart() {
checkState(State.OPEN);
state = State.BINARY_FULL_WRITING;
}
public synchronized void textPartialStart() {
checkState(State.OPEN, State.TEXT_PARTIAL_READY);
state = State.TEXT_PARTIAL_WRITING;
}
public synchronized void textStart() {
checkState(State.OPEN);
state = State.TEXT_FULL_WRITING;
}
public synchronized void complete(boolean last) {
if (last) {
checkState(State.TEXT_PARTIAL_WRITING, State.TEXT_FULL_WRITING,
State.BINARY_PARTIAL_WRITING, State.BINARY_FULL_WRITING,
State.STREAM_WRITING, State.WRITER_WRITING);
state = State.OPEN;
} else {
checkState(State.TEXT_PARTIAL_WRITING, State.BINARY_PARTIAL_WRITING,
State.STREAM_WRITING, State.WRITER_WRITING);
if (state == State.TEXT_PARTIAL_WRITING) {
state = State.TEXT_PARTIAL_READY;
} else if (state == State.BINARY_PARTIAL_WRITING){
state = State.BINARY_PARTIAL_READY;
} else if (state == State.WRITER_WRITING) {
// NO-OP. Leave state as is.
} else if (state == State.STREAM_WRITING) {
// NO-OP. Leave state as is.
} else {
// Should never happen
// The if ... else ... blocks above should cover all states
// permitted by the preceding checkState() call
throw new IllegalStateException(
"BUG: This code should never be called");
}
}
}
private void checkState(State... required) {
for (State state : required) {
if (this.state == state) {
return;
}
}
throw new IllegalStateException(
sm.getString("wsRemoteEndpoint.wrongState", this.state));
}
}
使用
org.apache.tomcat.websocket.WsRemoteEndpointImplBase#sendString
StateMachine stateMachine = new StateMachine();
stateMachine.textStart();
// to do something
stateMachine.complete(last);