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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to remove duplicate values from PHP array using regular expressions: Use regular expression /(.*)(.+)/i to match and replace duplicates. Iterate through the array elements and check for matches using preg_match. If it matches, skip the value; otherwise, add it to a new array with no duplicate values.

1. Programming can be used to develop various software and applications, including websites, mobile applications, games, and data analysis tools. Its application fields are very wide, covering almost all industries, including scientific research, health care, finance, education, entertainment, etc. 2. Learning programming can help us improve our problem-solving skills and logical thinking skills. During programming, we need to analyze and understand problems, find solutions, and translate them into code. This way of thinking can cultivate our analytical and abstract abilities and improve our ability to solve practical problems.

Build browser-based applications with Golang Golang combines with JavaScript to build dynamic front-end experiences. Install Golang: Visit https://golang.org/doc/install. Set up a Golang project: Create a file called main.go. Using GorillaWebToolkit: Add GorillaWebToolkit code to handle HTTP requests. Create HTML template: Create index.html in the templates subdirectory, which is the main template.

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

C is an ideal choice for beginners to learn system programming. It contains the following components: header files, functions and main functions. A simple C program that can print "HelloWorld" needs a header file containing the standard input/output function declaration and uses the printf function in the main function to print. C programs can be compiled and run by using the GCC compiler. After you master the basics, you can move on to topics such as data types, functions, arrays, and file handling to become a proficient C programmer.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

C++ programming puzzles cover algorithm and data structure concepts such as Fibonacci sequence, factorial, Hamming distance, maximum and minimum values of arrays, etc. By solving these puzzles, you can consolidate C++ knowledge and improve algorithm understanding and programming skills.
