v/vlib/net/socket_test.v

107 lines
2.3 KiB
V
Raw Normal View History

import net
2019-06-30 16:11:55 +02:00
fn setup() (net.Socket, net.Socket, net.Socket) {
2020-11-14 07:23:22 +01:00
server := net.listen(0) or {
panic(err)
}
server_port := server.get_port()
2020-11-14 07:23:22 +01:00
client := net.dial('127.0.0.1', server_port) or {
panic(err)
}
socket := server.accept() or {
panic(err)
}
2020-07-02 21:27:36 +02:00
$if debug_peer_ip ? {
2020-11-14 07:23:22 +01:00
ip := socket.peer_ip() or {
'$err'
}
2020-07-02 21:27:36 +02:00
eprintln('socket peer_ip: $ip')
2020-11-14 07:23:22 +01:00
}
return server, client, socket
}
fn cleanup(server &net.Socket, client &net.Socket, socket &net.Socket) {
2020-11-14 07:23:22 +01:00
server.close() or { }
client.close() or { }
socket.close() or { }
}
fn test_socket() {
server, client, socket := setup()
2020-11-14 07:23:22 +01:00
defer {
cleanup(server, client, socket)
}
message := 'Hello World'
2020-11-14 07:23:22 +01:00
socket.send(message.str, message.len) or {
assert false
}
$if debug {
println('message send: $message')
}
$if debug {
println('send socket: $socket.sockfd')
}
bytes, blen := client.recv(1024)
received := tos(bytes, blen)
2020-11-14 07:23:22 +01:00
$if debug {
println('message received: $received')
}
$if debug {
println('client: $client.sockfd')
}
assert message == received
2020-11-14 07:23:22 +01:00
}
fn test_socket_read_line() {
server, client, socket := setup()
defer {
cleanup(server, client, socket)
}
message1, message2 := 'message1', 'message2'
message := '$message1\n$message2'
socket.write(message) or {
assert false
}
line1, line2 := client.read_line(), client.read_line()
assert line1 != message1
assert line1.trim_space() == message1
assert line2 != message2
assert line2.trim_space() == message2
}
fn test_socket_write() {
server, client, socket := setup()
2020-11-14 07:23:22 +01:00
defer {
cleanup(server, client, socket)
}
message1 := 'a message 1'
2020-11-14 07:23:22 +01:00
socket.write(message1) or {
assert false
}
line1 := client.read_line()
assert line1 != message1
assert line1.trim_space() == message1
}
2020-05-20 21:47:03 +02:00
fn test_socket_write_fail_without_panic() {
server, client, socket := setup()
2020-11-14 07:23:22 +01:00
defer {
cleanup(server, client, socket)
}
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
2020-11-14 07:23:22 +01:00
client.close() or { }
$if solaris {
return
}
// TODO: fix segfaulting on Solaris
for i := 0; i < 3; i++ {
socket.write(message2) or {
println('write to a socket without a recipient should produce an option fail: $err | $message2')
assert true
}
}
}