📜  Socket.IO-Hello World(1)

📅  最后修改于: 2023-12-03 15:20:10.727000             🧑  作者: Mango

Socket.IO-Hello World

Socket.IO is a JavaScript library for real-time web applications. It enables real-time bidirectional event-based communication between servers and clients. In this "Hello World" tutorial, we will create a simple server and client which exchange greetings in real-time.

Requirements

To follow this tutorial, you need to have the following:

  • Node.js (version 6 or later)
  • npm (version 3 or later)
  • A text editor
Setting up the project
  1. Open a terminal or command prompt and create a new directory for the project:
mkdir socketio-hello-world
cd socketio-hello-world
  1. Initialize the project with npm:
npm init -y

This will create a package.json file in the directory with default settings.

  1. Install the necessary dependencies:
npm install express socket.io

This will install the Express and Socket.IO libraries which we will use in our project.

Creating the server
  1. Create a new file called server.js in the project directory.

  2. Add the following code to the file:

const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);

app.use(express.static(__dirname + '/public'));

io.on('connection', (socket) => {
  console.log('a user connected');

  socket.on('disconnect', () => {
    console.log('user disconnected');
  });

  socket.on('greeting', (msg) => {
    console.log('received greeting: ' + msg);
    io.emit('greeting', 'Hello from server!');
  });
});

http.listen(3000, () => {
  console.log('listening on *:3000');
});

This code sets up an Express server, creates a Socket.IO instance on top of it, and listens for incoming connections.

When a client connects, the server logs a message to the console and sets up event listeners for the disconnect and greeting events.

When the client emits a greeting event with a message, the server logs the message to the console and broadcasts a greeting event with a "Hello from server!" message to all connected clients.

Creating the client
  1. Create a new file called index.html in the public directory.

  2. Add the following code to the file:

<!DOCTYPE html>
<html>
<head>
  <title>Socket.IO-Hello World</title>
  <script src="/socket.io/socket.io.js"></script>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
  <h1>Welcome to Socket.IO-Hello World!</h1>
  <input type="text" id="greeting-input" placeholder="Enter your greeting...">
  <button id="greeting-btn">Send Greeting</button>
  <p id="greeting-output"></p>

  <script>
    const socket = io();

    $('#greeting-btn').click(() => {
      const msg = $('#greeting-input').val();
      socket.emit('greeting', msg);
    });

    socket.on('greeting', (msg) => {
      $('#greeting-output').text(msg);
    });
  </script>
</body>
</html>

This code creates a simple HTML page with an input box and a button which the user can use to send a greeting to the server.

The page includes scripts for the Socket.IO library and jQuery. When the page loads, it creates a Socket.IO instance and sets up event listeners for the greeting event.

When the user clicks the button, the client emits a greeting event with the message entered in the input box.

When the client receives a greeting event from the server, it updates the output message on the page.

Running the project
  1. Open a terminal or command prompt and navigate to the project directory.

  2. Run the server:

node server.js
  1. Open a web browser and navigate to http://localhost:3000.

  2. Enter a greeting in the input box and click the "Send Greeting" button.

  3. Verify that the server responds with "Hello from server!".

Congratulations! You have created a simple Socket.IO application which exchanges greetings in real-time between a client and a server. From this starting point, you can explore the many features of Socket.IO and build more complex applications.