Home Web Front-end JS Tutorial How to implement a chat room using socket.io

How to implement a chat room using socket.io

Jun 14, 2018 am 11:27 AM
socket.io chatroom

This article mainly introduces the use of socket.io to implement a simple chat room case, which has certain reference value. Interested friends can refer to it.

The example in this article shares the socket.io implementation with everyone. The specific code of the simple chat room is for your reference. The specific content is as follows

1. Client [index.html] code:

<body>
  <h3>socket简例</h3>
  <hr>
  <p id = &#39;app&#39;>
    <p>
      <p>
        <ul>
          <li v-for = &#39;item in msgs&#39;>
            {{item.name}}说:{{item.content}}
          </li>
        </ul>
      </p>
      <p>
        <p><input type="text" v-model = &#39;msg&#39;><button @click = &#39;m_send()&#39;>发送</button></p>
      </p>
    </p>
  </p>

  <script type="text/javascript" src = &#39;https://cdn.bootcss.com/vue/2.5.9/vue.min.js&#39;></script>
  <script type="text/javascript" src = &#39;https://cdn.bootcss.com/socket.io/1.7.3/socket.io.min.js&#39;></script>
  <script type="text/javascript">

    var _vm = new Vue({
      data : {
        name : &#39;用户&#39;,
        msg : &#39;&#39;,
        msgs : [],
      },
      methods : {
        m_send : function() {

          // 向客户端发送消息
          socket_client.emit(&#39;say_client&#39;, {
            name : this.name,
            content : this.msg
          }) ;
          this.msg = &#39;&#39; ;
        }
      }
    }).$mount(&#39;#app&#39;) ;


    // socket服务器
    var socket_client = io.connect(&#39;http://127.0.0.1:3000&#39;) ; 

    /**
     * 监听服务端发来的消息
     *
     * 1、“say_server”是客户端发出信息时的key值
     * 2、“res”是客户端传来的value值
     */ 
    socket_client.on(&#39;say_server&#39; ,function(res){

      console.log(&#39;服务端发来的消息为:&#39;, res) ;

      _vm.msgs.push(res);
    });

  </script>
</body>
Copy after login

2. Server [app.js] code:

const http = require(&#39;http&#39;) ;
const server = http.createServer() ;

// web服务器
const express = require(&#39;express&#39;) ;
const app = express();

app.use(express.static(__dirname + &#39;/public&#39;));

app.listen(8888, function () {
  console.log(&#39;web服务器成功启动了,IP:127.0.0.1,端口号:8888&#39;) ;
});


// socket服务器

const socketio = require(&#39;socket.io&#39;) ;
const socket_server = socketio(server) ;

// 建立和客户端的socket连接
socket_server.on(&#39;connection&#39;, function(client) {

// console.log(client) ;          // 查看连接进来的客户端对象内容  
// console.log(Object.keys(client)) ;    // 查看连接进来的客户端对象的关键key值

  /**
   * 监听客户端发来的消息
   *
   * 1、“say_client”是客户端发出信息时的key值
   * 2、“res”是客户端传来的value值
   */ 
  client.on(&#39;say_client&#39;, function(res) {
    console.log(&#39;客户端发来的消息为:&#39;, res) ;

    // 向客户端发送消息
    socket_server.emit(&#39;say_server&#39;, res) ;
  }) ;
}) ;


server.listen(3000, function() {
  console.log(&#39;socket服务器成功启动了,IP:127.0.0.1,端口号:3000&#39;) ;  
}) ;
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How should webpack handle styles?

How to generate word images in js

What are the reference methods for libraries in jQuery

The above is the detailed content of How to implement a chat room using socket.io. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement a simple chat room function using MySQL and Java How to implement a simple chat room function using MySQL and Java Sep 21, 2023 pm 05:13 PM

How to use MySQL and Java to implement a simple chat room function Introduction: With the prevalence of social media today, people increasingly rely on online chat to communicate and share information. How to implement a simple chat room function using MySQL and Java is a very interesting and practical project. This article will introduce how to use MySQL and Java to implement this function, and provide specific code examples. 1. Build a database First, we need to create a database in MySQL to store chat room related information.

How to develop Websocket chat room using Go language How to develop Websocket chat room using Go language Dec 14, 2023 pm 01:46 PM

How to use Go language to develop a Websocket chat room. Websocket is a real-time communication protocol that allows two-way communication between the server and the client by establishing a connection. Websocket is a very good choice when developing chat rooms because it enables real-time message exchange and provides efficient performance. This article will introduce how to develop a simple Websocket chat room using Go language and provide some specific code examples. 1. Preparation 1. Install Go

Build a real-time chat room based on JavaScript Build a real-time chat room based on JavaScript Aug 10, 2023 pm 11:18 PM

Building a real-time chat room based on JavaScript With the rapid development of the Internet, people are paying more and more attention to instant messaging and real-time interactive experience. As a common instant messaging tool, real-time chat rooms are very important to both individuals and businesses. This article will introduce how to build a simple real-time chat room using JavaScript and provide corresponding code examples. We first need a front-end page as the UI interface of the chat room. Here is an example of a simple HTML structure: &lt;!DOCTYPE

ThinkPHP6 Chat Room Development Guide: Implementing Real-time Communication Functions ThinkPHP6 Chat Room Development Guide: Implementing Real-time Communication Functions Aug 12, 2023 pm 02:31 PM

ThinkPHP6 Chat Room Development Guide: Implementing Real-time Communication Function Introduction: With the rapid development of the Internet, the demand for real-time communication is also increasing. As a common method of real-time communication, chat rooms have received widespread attention and use. This article will provide you with a simple and fast method to implement real-time communication functions by using the ThinkPHP6 framework. 1. Environment configuration: Before starting, we need to configure the development environment. Make sure you have PHP and ThinkPHP6 framework installed. At the same time, this article will make

Develop chat room function using php and Websocket Develop chat room function using php and Websocket Dec 02, 2023 am 11:08 AM

Using PHP and Websocket to develop chat room functions Introduction: With the rapid development of the Internet, chat rooms have become one of the important means for people to communicate and socialize in daily life. Using PHP and Websocket technology to develop a chat room function can achieve real-time two-way communication and provide users with a smoother and more convenient chat experience. This article will introduce how to use PHP and Websocket to implement a simple chat room, and provide specific code examples. 1. Preparation: Before starting development, we need to ensure

How to solve the pitfall of nginx proxy socket.io service How to solve the pitfall of nginx proxy socket.io service May 13, 2023 pm 12:43 PM

nginx proxies two socket.io servers. The working mode of socket.io is polling and upgrading to websocket. When requesting services through nginx, a large number of 400 errors appear. Sometimes it can be upgraded to websocket, and sometimes it keeps reporting errors. But when accessing directly through ip+port, it is 100% successful. Analyzing sidsid is the key to our problem. When initially creating a connection (polling mode is simulating a long connection), the client will initiate such a request: https://***/?eio=3&transport=polling&t=154082071

Swoole in action: quickly create a chat room based on WebSocket Swoole in action: quickly create a chat room based on WebSocket Jun 14, 2023 pm 04:20 PM

In the Internet era, chat rooms have become an important place for people to communicate and socialize. The emergence of WebSocket technology has made real-time communication smoother and more stable. Today, we introduce how to use the Swoole framework to quickly build a chat room based on WebSocket. Swoole is a high-performance PHP coroutine network communication framework, written in C language, integrating asynchronous IO, coroutine, network communication and other functions, making PHP code like Node.js

PHP and WebSocket integration realize the development of real-time chat room PHP and WebSocket integration realize the development of real-time chat room Jun 25, 2023 pm 01:13 PM

In the world of web development, live chat features have become increasingly popular. It helps users easily interact in real time and enhance communication and understanding. In order to implement real-time chat, we need to use the WebSocket protocol and need a programming language that can handle WebSocket requests. In this article, we will introduce how to implement the development of real-time chat rooms using PHP and WebSocket integration. WebSocket is a full-duplex communication protocol that enables real-time communication between a browser and a server.

See all articles