@@ -88,24 +88,25 @@ def state(self) -> ConnectionState:
88
88
89
89
def send (self , event : Event ) -> bytes :
90
90
data = b""
91
- if isinstance (event , Message ):
91
+ if isinstance (event , Message ) and self . state == ConnectionState . OPEN :
92
92
data += self ._proto .send_data (event .data , event .message_finished )
93
- elif isinstance (event , Ping ):
93
+ elif isinstance (event , Ping ) and self . state == ConnectionState . OPEN :
94
94
data += self ._proto .ping (event .payload )
95
- elif isinstance (event , Pong ):
95
+ elif isinstance (event , Pong ) and self . state == ConnectionState . OPEN :
96
96
data += self ._proto .pong (event .payload )
97
- elif isinstance (event , CloseConnection ):
98
- if self .state not in {ConnectionState .OPEN , ConnectionState .REMOTE_CLOSING }:
99
- raise LocalProtocolError (
100
- "Connection cannot be closed in state %s" % self .state
101
- )
97
+ elif isinstance (event , CloseConnection ) and self .state in {
98
+ ConnectionState .OPEN ,
99
+ ConnectionState .REMOTE_CLOSING ,
100
+ }:
102
101
data += self ._proto .close (event .code , event .reason )
103
102
if self .state == ConnectionState .REMOTE_CLOSING :
104
103
self ._state = ConnectionState .CLOSED
105
104
else :
106
105
self ._state = ConnectionState .LOCAL_CLOSING
107
106
else :
108
- raise LocalProtocolError (f"Event { event } cannot be sent." )
107
+ raise LocalProtocolError (
108
+ f"Event { event } cannot be sent in state { self .state } ."
109
+ )
109
110
return data
110
111
111
112
def receive_data (self , data : Optional [bytes ]) -> None :
0 commit comments