java socket programming
Can I write a socket programming to provide services to the web clients? I did it using servlet, but I want to do it using java.net API. Please give me a sample code of some program, such that I can access that simply by mentioning URL at the address bar of a开发者_开发知识库ny web browser.
I suggest you look at the source for jetty. It is the simplest web server I can think of. If you want an ultra basic web server, you can do this with plain sockets, however the HTTP protocol is quite complex and using a web server library to handle all the details is likely to be the best approach.
If you want to be able to receive requests typed into a web browser, you need to do a couple things.
-Set the socket to listen on port 80 -Receive/parse/process HTML requests -Return an HTML response across the socket
Rather than write the code for you, here is some pseudocode
//setup socket on port 80
socket.lisen();
while(true)
{
newsocket = socket.accept();
new thread(process(newsocket));
}
The most complicated part, I think, will be handling the HTML, processing the request, and generating a response. After that, just send it back over the socket.
Considering how many libraries are out there for this sort of thing, I wouldn't reccommend writing one from scratch.
The problem is that "web client" is just a browser, so you don't have direct access to TCP/IP. Few options:
- HTML5 WebSockets (only modern browsers)
- flash helper (there are javascript wrappers)
- java applet helper (there are javascript wrappers)
- some tricks based on ajax pooling
精彩评论