The socket programming here does not mean using the XMLHttpRequest object, but actually creating a socket to implement and send and receive data. Use JavaScript to invoke Java's NIO interface to implement socket programming.
Implement a simple echoserver, create a file: Echoserver.js
var socket = __import__ (' socket ', NULL, {})//import socket Library ...
var server = new socket. Socketserver (' 127.0.0.1 ', 8000)//Create a socket Server.
Server.on (' Listen ', function (server) {//join server to start listening for events
Print (' Event Listen on server: ' + server.localaddress + ', port: ' + server.localport ')
})
Server.on (' clientclosed ', function (client) {
Print (' Event clientclosed on server: ' + client.address + ', port: ' + client.port ')
})
Server.on (' Closed ', function (socket) {
Print (' Event closed on server ')
})
Server.on (' Accept ', function (client) {//A new client connection
Print (' New client: ' + client.address + ', port: ' + client.port ')
Client.on (' read ', function (s) {//clinet has data readable.
var input = S.read ();
Print (' Read data: ' + input ')
S.write (Input)//write data to,
});
Client.on (' Closed ', function (s) {
Print (' Bye bye client. ')
S.write (' input ')
});
})
Server.listen ("127.0.0.1", 8000)//monitor a port and blocking until the server side is closed.
Run:
# JS Echoserver.js
Event Listen on Server:localhost, port:8000
Open a new Window entry
#telnet 127.0.0.1 8000
# Service-side display
Event Listen on Server:localhost, port:8000
New Client:localhost, port:1978
Event:read
Read Data:a
Event:read
Read Data:b
Event:read
Read Data:c
The test server connection succeeded.
Run the above code, also need a running environment and socket library, can go to http://code.google.com/p/js-shell/downloads/list download a night build. This article links http://www.cxybl.com/html/wyzz/JavaScript_Ajax/20120723/32103.html
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.