1 /* vim:set ts=4 sw=4 et cindent: */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #include "TestCommon.h"
8 #include "nsIServiceManager.h"
9 #include "nsIServerSocket.h"
10 #include "nsISocketTransport.h"
11 #include "nsNetUtil.h"
12 #include "nsStringAPI.h"
16 #if defined(PR_LOGGING)
18 // set NSPR_LOG_MODULES=Test:5
20 static PRLogModuleInfo
*gTestLog
= nullptr;
22 #define LOG(args) PR_LOG(gTestLog, PR_LOG_DEBUG, args)
24 class MySocketListener
: public nsIServerSocketListener
27 virtual ~MySocketListener() {}
30 NS_DECL_THREADSAFE_ISUPPORTS
31 NS_DECL_NSISERVERSOCKETLISTENER
36 NS_IMPL_ISUPPORTS(MySocketListener
, nsIServerSocketListener
)
39 MySocketListener::OnSocketAccepted(nsIServerSocket
*serv
,
40 nsISocketTransport
*trans
)
42 LOG(("MySocketListener::OnSocketAccepted [serv=%p trans=%p]\n", serv
, trans
));
48 trans
->GetPort(&port
);
50 LOG((" -> %s:%d\n", host
.get(), port
));
52 nsCOMPtr
<nsIInputStream
> input
;
53 nsCOMPtr
<nsIOutputStream
> output
;
56 rv
= trans
->OpenInputStream(nsITransport::OPEN_BLOCKING
, 0, 0, getter_AddRefs(input
));
60 rv
= trans
->OpenOutputStream(nsITransport::OPEN_BLOCKING
, 0, 0, getter_AddRefs(output
));
67 rv
= input
->Read(buf
, sizeof(buf
), &n
);
71 const char response
[] = "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\nFooooopy!!\r\n";
72 rv
= output
->Write(response
, sizeof(response
) - 1, &n
);
82 MySocketListener::OnStopListening(nsIServerSocket
*serv
, nsresult status
)
84 LOG(("MySocketListener::OnStopListening [serv=%p status=%x]\n", serv
, status
));
90 MakeServer(int32_t port
)
93 nsCOMPtr
<nsIServerSocket
> serv
= do_CreateInstance(NS_SERVERSOCKET_CONTRACTID
, &rv
);
97 rv
= serv
->Init(port
, true, 5);
101 rv
= serv
->GetPort(&port
);
104 LOG((" listening on port %d\n", port
));
106 rv
= serv
->AsyncListen(new MySocketListener());
111 main(int argc
, char* argv
[])
113 if (test_common_init(&argc
, &argv
) != 0)
116 nsresult rv
= (nsresult
)-1;
118 printf("usage: %s <port>\n", argv
[0]);
122 #if defined(PR_LOGGING)
123 gTestLog
= PR_NewLogModule("Test");
127 * The following code only deals with XPCOM registration stuff. and setting
128 * up the event queues. Copied from TestSocketIO.cpp
131 rv
= NS_InitXPCOM2(nullptr, nullptr, nullptr);
132 if (NS_FAILED(rv
)) return -1;
135 rv
= MakeServer(atoi(argv
[1]));
137 LOG(("MakeServer failed [rv=%x]\n", rv
));
141 // Enter the message pump to allow the URL load to proceed.
143 } // this scopes the nsCOMPtrs
144 // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM
145 NS_ShutdownXPCOM(nullptr);