132
|
1 /*******************************************************************************
|
|
2
|
|
3 Shows how to create a basic socket server, and how to talk to
|
|
4 it from a socket client. Note that both the server and client
|
|
5 are entirely simplistic, and therefore this is for illustration
|
|
6 purposes only. See HttpServer for something more robust.
|
|
7
|
|
8 *******************************************************************************/
|
|
9
|
|
10 private import tango.core.Thread;
|
|
11
|
|
12 private import tango.io.Console;
|
|
13
|
|
14 private import tango.net.ServerSocket,
|
|
15 tango.net.SocketConduit;
|
|
16
|
|
17 /*******************************************************************************
|
|
18
|
|
19 Create a socket server, and have it respond to a request
|
|
20
|
|
21 *******************************************************************************/
|
|
22
|
|
23 void main()
|
|
24 {
|
|
25 const int port = 8080;
|
|
26
|
|
27 // thread body for socket-listener
|
|
28 void run()
|
|
29 {
|
|
30 auto server = new ServerSocket (new InternetAddress(port));
|
|
31
|
|
32 // wait for requests
|
|
33 auto request = server.accept;
|
|
34
|
|
35 // write a response
|
|
36 request.output.write ("server replies 'hello'");
|
|
37 }
|
|
38
|
|
39 // start server in a separate thread, and wait for it to start
|
|
40 (new Thread (&run)).start;
|
|
41 Thread.sleep (0.250);
|
|
42
|
|
43 // make a connection request to the server
|
|
44 auto request = new SocketConduit;
|
|
45 request.connect (new InternetAddress("localhost", port));
|
|
46
|
|
47 // wait for and display response (there is an optional timeout)
|
|
48 char[64] response;
|
|
49 auto len = request.input.read (response);
|
|
50 Cout (response[0..len]).newline;
|
|
51
|
|
52 request.close;
|
|
53 }
|