@@ -5,6 +5,8 @@ module Sip2
5
5
# Sip2 Connection
6
6
#
7
7
class Connection
8
+ LINE_SEPARATOR = "\r "
9
+
8
10
@connection_modules = [ ]
9
11
10
12
class << self
@@ -18,12 +20,17 @@ def add_connection_module(module_name)
18
20
include Messages ::Login
19
21
include Messages ::PatronInformation
20
22
21
- def initialize ( socket , ignore_error_detection )
23
+ def initialize ( socket : , ignore_error_detection : false )
22
24
@socket = socket
23
25
@ignore_error_detection = ignore_error_detection
24
26
@sequence = 1
25
27
end
26
28
29
+ def send_message ( message )
30
+ write_with_timeout message
31
+ read_with_timeout
32
+ end
33
+
27
34
def method_missing ( method_name , *args )
28
35
if Connection . connection_modules . include? ( method_name . to_sym )
29
36
send_and_handle_message ( method_name , *args )
@@ -47,13 +54,27 @@ def send_and_handle_message(message_type, *args)
47
54
send "handle_#{ message_type } _response" , response
48
55
end
49
56
50
- def send_message ( message )
51
- @socket . send_with_timeout message
52
- @socket . gets_with_timeout
57
+ def write_with_timeout ( message , separator : LINE_SEPARATOR )
58
+ ::Timeout . timeout connection_timeout , WriteTimeout do
59
+ @socket . write message + separator
60
+ end
61
+ end
62
+
63
+ def read_with_timeout ( separator : LINE_SEPARATOR )
64
+ ::Timeout . timeout connection_timeout , ReadTimeout do
65
+ @socket . gets ( separator ) &.chomp ( separator )
66
+ end
67
+ end
68
+
69
+ def connection_timeout
70
+ # We want the underlying connection where the timeout is configured,
71
+ # so if we're dealing with an SSLSocket then we need to unwrap it
72
+ io = @socket . respond_to? ( :io ) ? @socket . io : @socket
73
+ io . connection_timeout || NonBlockingSocket ::DEFAULT_TIMEOUT
53
74
end
54
75
55
76
def with_error_detection ( message )
56
- message + ' |AY' + @sequence . to_s
77
+ " #{ message } |AY#{ @sequence } "
57
78
end
58
79
59
80
def with_checksum ( message )
@@ -72,7 +93,7 @@ def checksum_for(message)
72
93
def sequence_and_checksum_valid? ( response )
73
94
return true if @ignore_error_detection
74
95
75
- sequence_regex = /^ (?<message>.*?AY(?<sequence>[0-9]+)AZ)(?<checksum>[A-F0-9]{4})$ /
96
+ sequence_regex = /\A (?<message>.*?AY(?<sequence>[0-9]+)AZ)(?<checksum>[A-F0-9]{4})\z /
76
97
match = response . strip . match sequence_regex
77
98
match &&
78
99
match [ :sequence ] == @sequence . to_s &&
0 commit comments