Java socket server: JavaScript socket server Side programming.

Source: Internet
Author: User
Tags implement socket client

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 (' ', 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 = ();
Print (' Read data: ' + input ')
S.write (Input)//write data to,
Client.on (' Closed ', function (s) {
Print (' Bye bye client. ')
S.write (' input ')
Server.listen ("", 8000)//monitor a port and blocking until the server side is closed.
# JS Echoserver.js
Event Listen on Server:localhost, port:8000
Open a new Window entry
#telnet 8000
# Service-side display
Event Listen on Server:localhost, port:8000
New Client:localhost, port:1978
Read Data:a
Read Data:b
Read Data:c
The test server connection succeeded.
Run the above code, also need a running environment and socket library, can go to download a night build. This article links

Related Article

Contact Us

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: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.