2019-09-23 22:17:06 +02:00
|
|
|
import net
|
2019-06-30 16:11:55 +02:00
|
|
|
|
2019-11-18 22:13:14 +01:00
|
|
|
fn setup() (net.Socket, net.Socket, net.Socket) {
|
|
|
|
server := net.listen(0) or { panic(err) }
|
2019-09-20 16:04:39 +02:00
|
|
|
server_port := server.get_port()
|
2019-11-18 22:13:14 +01:00
|
|
|
client := net.dial('127.0.0.1', server_port) or { panic(err) }
|
|
|
|
socket := server.accept() or { panic(err) }
|
|
|
|
return server, client, socket
|
|
|
|
}
|
|
|
|
|
|
|
|
fn cleanup(server &net.Socket, client &net.Socket, socket &net.Socket) {
|
|
|
|
server.close() or {}
|
|
|
|
client.close() or {}
|
|
|
|
socket.close() or {}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn test_socket() {
|
|
|
|
server, client, socket := setup()
|
2019-09-20 16:04:39 +02:00
|
|
|
message := 'Hello World'
|
2019-11-18 22:13:14 +01:00
|
|
|
socket.send(message.str, message.len) or { assert false }
|
2019-09-23 18:48:18 +02:00
|
|
|
$if debug { println('message send: $message') }
|
|
|
|
$if debug { println('send socket: $socket.sockfd') }
|
2019-09-20 16:04:39 +02:00
|
|
|
|
2019-09-23 22:17:06 +02:00
|
|
|
bytes, blen := client.recv(1024)
|
2019-09-23 18:48:18 +02:00
|
|
|
received := tos(bytes, blen)
|
|
|
|
$if debug { println('message received: $received') }
|
|
|
|
$if debug { println('client: $client.sockfd') }
|
2020-05-20 21:47:03 +02:00
|
|
|
|
2019-09-20 16:04:39 +02:00
|
|
|
assert message == received
|
2019-11-18 22:13:14 +01:00
|
|
|
cleanup(server, client, socket)
|
|
|
|
}
|
2019-09-20 16:04:39 +02:00
|
|
|
|
2019-11-18 22:13:14 +01:00
|
|
|
fn test_socket_write() {
|
|
|
|
server, client, socket := setup()
|
|
|
|
message1 := 'a message 1'
|
|
|
|
socket.write(message1) or { assert false }
|
|
|
|
line1 := client.read_line()
|
|
|
|
assert line1 != message1
|
|
|
|
assert line1.trim_space() == message1
|
|
|
|
cleanup(server, client, socket)
|
|
|
|
}
|
2020-05-20 21:47:03 +02:00
|
|
|
|
2019-11-18 22:13:14 +01:00
|
|
|
fn test_socket_write_fail_without_panic() {
|
|
|
|
server, client, socket := setup()
|
|
|
|
message2 := 'a message 2'
|
|
|
|
// ensure that socket.write (i.e. done on the server side)
|
|
|
|
// continues to work, even when the client side has been disconnected
|
|
|
|
// this test is important for a stable long standing server
|
2019-11-04 00:38:49 +01:00
|
|
|
client.close() or {}
|
2020-03-21 09:48:02 +01:00
|
|
|
$if solaris { return } // TODO: fix segfaulting on Solaris
|
2020-05-20 21:47:03 +02:00
|
|
|
for i:=0; i<3; i++ {
|
2019-11-18 22:13:14 +01:00
|
|
|
socket.write(message2) or {
|
|
|
|
println('write to a socket without a recipient should produce an option fail: $err | $message2')
|
|
|
|
assert true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
cleanup(server, client, socket)
|
2019-09-23 22:17:06 +02:00
|
|
|
}
|