Home >Web Front-end >JS Tutorial >How to establish a WebSocket connection

How to establish a WebSocket connection

WBOY
WBOYOriginal
2024-02-18 10:29:051384browse

How to establish a WebSocket connection

WebSocket is a full-duplex communication protocol that allows the establishment of a persistent connection between the client and the server for real-time data transmission. In this article, you will learn more about connecting WebSocket using JavaScript and provide specific code examples.

First, you need to create a WebSocket instance on the client side. This can be achieved by using the new WebSocket(url) method, where url is the address of the WebSocket server. For example, if the WebSocket server is running at ws://localhost:8080, you can create a WebSocket instance through the following code:

var socket = new WebSocket("ws://localhost:8080");

After the connection is established, the WebSocket instance will trigger several events, including open, message, error and close. Various situations can be handled by adding listeners to these events. For example, the following code demonstrates how to handle the situation when the connection is established successfully, the message is received, and the connection is closed:

socket.addEventListener("open", function(event) {
  console.log("WebSocket 连接已建立");
});

socket.addEventListener("message", function(event) {
  var message = event.data;
  console.log("接收到消息: " + message);
});

socket.addEventListener("error", function(event) {
  console.error("WebSocket 错误: ", event);
});

socket.addEventListener("close", function(event) {
  console.log("WebSocket 连接已关闭");
});

To send a message to a WebSocket server, you can use the WebSocket instance's send() method. This method accepts a string parameter, which is sent to the server. The following is a sample code:

var messageToSend = "Hello, WebSocket!";
socket.send(messageToSend);

The above code sends the message "Hello, WebSocket!" to the WebSocket server. After receiving the message, the server can perform corresponding processing and send a reply message to the client.

For server-side implementation, different programming languages ​​and frameworks can be used to create WebSocket servers. Taking Node.js as an example, you can use the ws module to create a WebSocket server. The following is a simple example of creating a WebSocket server using Node.js:

const WebSocket = require('ws');

const server = new WebSocket.Server({ port: 8080 });

server.on('connection', function(socket) {
  console.log('有新的 WebSocket 连接');

  socket.on('message', function(message) {
    console.log('接收到消息: ' + message);
    // 处理消息并发送回复
    socket.send('你好,客户端!');
  });

  socket.on('close', function() {
    console.log('WebSocket 连接已关闭');
  });
});

The above code creates a WebSocket server and outputs a message when a new connection is established. After receiving the message sent by the client, the server sends a reply message back to the client.

In summary, to connect to WebSocket, you need to use JavaScript to create a WebSocket instance on the client side, and add event listeners to handle events such as connection establishment, message reception, and connection closing. To send a message, you can use the send() method of the WebSocket instance. In the server-side implementation, different programming languages ​​and frameworks can be used to create WebSocket servers that process client requests and reply messages by listening to connection events and message events. The above provides specific code examples, I hope it will help you understand WebSocket connections.

The above is the detailed content of How to establish a WebSocket connection. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn