/tutorial/net/sockets.e
Specman e | 109 lines | 80 code | 8 blank | 21 comment | 3 complexity | ee06075f6ce0106ad0642560e4240f89 MD5 | raw file
1class SOCKETS 2 -- 3 -- This is the first tutorial class to look at, because it gives the most simple examples. 4 -- 5 6create {ANY} 7 make 8 9feature {} 10 make 11 local 12 tcp: TCP_ACCESS; host: HOST; ip: IPV4_ADDRESS 13 do 14 -- The example just tries to connect to a well-known ftp server 15 create host.make(once "ftp.funet.fi") 16 create tcp.make(host, 21, True) 17 test_socket(tcp) 18 -- Now the following lines start a real server, listening on port 2001. 19 create ip.make(127, 0, 0, 1) 20 create tcp.make(ip, 2001, True) 21 test_server(tcp) 22 end 23 24 test_socket (access: TCP_ACCESS) 25 -- First tutorial: simple network connection 26 local 27 ios: SOCKET_INPUT_OUTPUT_STREAM 28 do 29 -- Create a stream connected to the address 30 ios := access.stream 31 if ios = Void then 32 std_error.put_line(access.error) 33 elseif ios.is_connected then 34 from 35 -- actively wait for enough characters to be available 36 until 37 ios.can_read_line 38 loop 39 end 40 ios.read_line 41 io.put_string(ios.last_string) 42 io.put_new_line 43 ios.disconnect 44 else 45 std_error.put_line("Socket not connected!") 46 end 47 end 48 49 test_server (access: TCP_ACCESS) 50 -- Second tutorial: create a server. This one is trivial, see MULTIPLEX_SERVER for a real-life 51 -- example 52 local 53 server: SOCKET_SERVER; job: SOCKET_SERVER_JOB 54 do 55 -- About the stack and the sequencer: see the sequencer tutorial 56 create stack.make 57 -- Create a server listening at the given address 58 server := access.server 59 -- Must test if the server is effectively listening (otherwise there was an error: address in use and 60 -- so on) 61 62 if server.can_connect then 63 -- Create a job that uses this server 64 create job.make(server, True) 65 -- Add a handler: the agent is called by the server when an incoming connection happens 66 job.when_connect(agent handle_connect(?)) 67 -- Add the job to the sequencer stack 68 stack.add_job(job) 69 io.put_string(once "Accepting connections on port ") 70 io.put_integer(access.port) 71 io.put_new_line 72 -- And we start the sequencer loop 73 stack.run 74 end 75 end 76 77feature {} 78 stack: LOOP_STACK 79 80 handle_connect (ios: SOCKET_INPUT_OUTPUT_STREAM) 81 -- Handle a connection to the server. Acts as an echo server. 82 local 83 stop: BOOLEAN; s: STRING 84 do 85 from 86 io.put_string(once "(new connection accepted)%N") 87 until 88 stop 89 loop 90 from 91 -- active wait 92 until 93 ios.can_read_line 94 loop 95 end 96 ios.read_line 97 s := ios.last_string 98 if not s.is_empty then 99 stop := s.same_as(once "stop") 100 ios.put_line(s) 101 end 102 end 103 ios.disconnect 104 io.put_string(once "(connection cancelled)%N") 105 -- This last line will stop the SERVER! 106 stack.break 107 end 108 109end -- class SOCKETS