投稿時間:2023-05-01 05:16:17 RSSフィード2023-05-01 05:00 分まとめ(20件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
海外TECH DEV Community Building a simple real-time chat app with Node.js and Socket.io https://dev.to/ndulue/building-a-simple-real-time-chat-app-with-nodejs-and-socketio-e9i Building a simple real time chat app with Node js and Socket ioCommunication is more important than ever in today s fast paced world Real time chat apps have become indispensable as the demand for quick and easy ways to engage with others increases But have you ever pondered how these apps are developed So no more wondering I ll walk you through the process of creating a simple real time chat app in this article providing you the ability to develop a platform for effortless collaboration IntroductionA real time chat application is a software that allows prompt communication between users over a network or the internet Such applications leverage WebSockets or long polling techniques to establish and maintain a persistent bidirectional communication channel between a client and a server allowing messages to be sent and also received in real time The client sends and also receives data to and from the server whenever it is available allowing messages to appear instantly on the user s screen This is in contrast to web applications where clients make requests to the server and wait for a response before displaying data to the user Developing a real time chat app necessitates proficiency in various areas of web development including front end and back end development as well as networking Knowledge of specific technologies and frameworks such as Node js Socket io and other WebSockets libraries is highly important to build such applications Common examples of real time chat applications are messaging platforms like Slack WhatsApp and Facebook Messenger Why choose Node js and Socket io Node js and Socket io offers a number of benefits which includes Real time functionality Socket io is a javascript library that supports real time bidirectional communication among clients and servers thereby making it an ideal choice for designing real time chat applications Socket io uses WebSockets under the hood which enables low latency real time data transfer Scalability Node js is designed to be highly scalable meaning it can handle an overwhelming number of simultaneous connections without lagging or becoming unresponsive making it the right choice for building real time chat applications that support thousands or even millions of users Cross platform compatibility Node js as a programming language is compatible with a number of operating systems including Windows Linux and macOS This means that engineers can code once and deploy it on multiple platforms making it easier and faster to develop and maintain real time chat applications across different devices and environments Setting up the project Installation of Node js and npmVisit the official Node js website Download the Node js installer for your operating system Windows macOS or Linux on the homepage Once the installer is downloaded run it and follow the on screen instructions to install Node js and npm on your system To verify that Node js and npm have been successfully installed open a command prompt Windows or terminal macOS or Linux and run the command to check the version of Node js that has been installed node vand then typenpm vto check the version of npm installed Setting up a Node js projectOpen your command terminal and navigate to the directory where you want to create your new Node js project Type the command to initialize a new Node js project npm initYou will be prompted to enter various details about your project such as the project name version description etc Ensure you follow the prompts and enter the required information If you re not sure about any of the prompts given you simply press Enter to accept the default values Once you ve entered all the required information npm will generate a package json file in your project directory This file will contain information about your project and its dependencies and is used by npm to manage your project s dependencies Installation of the necessary dependenciesRun the following command to install the dependencies listed in the package json file npm installThis will install the dependencies listed in the package json file in the node modules folder in your project directory If you want to install a specific dependency run the following command npm install lt package name gt saveReplace with the name of the package you want to install The ーsave flag will add the package to your project s dependencies in the package json file Developing the chat server Setting up the server using the Express js frameworkRun the command on your command promptnpm i expressThis will install Express js as a dependency for your project using the npm package manager Now create a new JavaScript file for your server and name it “server js Import the Express js module by requiring it at the top of your JavaScript file using the following code const express require express Instantiate the Express application by calling the express function and assigning it to a variable const app express Set up routes on your server by specifying endpoints for the HTTP methods you want to handle this includes GET POST PUT and DELETE methods Here is an example a GET endpoint at the root of your server app get req res gt res send Welcome Start the server by calling the “listen method on the Express application instance passing in the port number “ your server will listen on as an argument app listen gt console log Server is listening on port Run your server by running the “node command along with the name of your server file in the terminal or command prompt For example to run a server saved in a file called “server js you would type “node server js Once your server is up and running you should be able to access it in your web browser by visiting “http localhost Setting up Socket io on the serverRun the command to install Socket io in your project directory as a dependency for your project using the npm package manager npm install socket ioImport both the Express js and Socket io modules by requiring them at the top of your JavaScript file using the following code const express require express const app express const http require http createServer app const io require socket io http Here Express js instance is wrapped with the HTTP server instance to create an HTTP server that can handle both WebSocket connections and regular HTTP requests Set up the connection event handler for Socket io which listens for incoming socket connections and executes a callback function whenever a connection is established io on connection socket gt console log Connected Proceed to set up event listeners for the different events that you want to handle on the server side such as “typing or “message To emit events to all connected clients use the “io emit method or to a specific client use the “socket emit method Here is an example of emitting a “message event to all connected clients io on connection socket gt console log Connected socket on message data gt console log Your Message data io emit message data Start the server by calling the “listen method on the http application instance passing in the port number “ your server will listen on as an argument http listen gt console log Server listening on port Once you have configured Socket io on your server you can use the socket object in your event listeners to communicate with connected clients in real time sending and receiving messages or data as needed Creating event listeners for incoming socket connectionsEstablish a connection event handler using the “io on method to listen for incoming socket connections Inside the callback function for the “io on method your event listeners can be created using the “socket on method io on connection socket gt console log A user connected socket on message data gt console log Received message data In this example we use the “socket on method to create a “message event listener for the newly connected client Whenever the client emits a “message event the callback function is executed and we log the received message to the console You can create multiple event listeners inside the connection event handler to handle various events from the clients When the client emits an event the corresponding event listener function is executed on the server allowing you to handle the event in real time and perform any necessary actions Setting up basic chat functionality with socket eventsTo set up basic chat functionality with Socket io events you can create event listeners to handle sending messages joining leaving rooms and other relevant actions Here is an example of how to create event listeners for these actions io on connection socket gt console log A user connected Join a room socket on joinRoom room gt console log socket id just joined room room socket join room io to room emit roomJoined socket id just joined the room Leave a room socket on leaveRoom room gt console log socket id has left room room socket leave room io to room emit roomLeft socket id has left the room Post a message to a specific room socket on messageToRoom data gt console log socket id posted a message to room data room data message io to data room emit message id socket id message data message Send a message to all connected clients socket on messageToAll data gt console log socket id sent a message to all clients data message io emit message id socket id message data message Disconnect event socket on disconnect gt console log socket id disconnected In this example we create a connection event listener that logs a message to the console when a new socket connection is made We also create event listeners for various actions inside the connection event listener First we create event listeners to handle both joining and leaving rooms When a client emits a “joinRoom event we use the “socket join method to add the client to the specified room and emit a “roomJoined event to all clients in the room Similarly when a client also emits a “leaveRoom event we use the “socket leave method to remove the client from the specified room and emit a “roomLeft event to all clients in the room Next we initialize event listeners to handle sending messages effectively We use the “io to method to emit the “message event to all clients in the room when a client emits the “messageToRoom event We also use the “io emit method to emit a “message event to all connected clients whenever a client emits a “messageToAll event Lastly an event listener is created to handle the “disconnect event which is emitted when a client gets disconnected from the server A message is logged indicating that the client is disconnected when this event is emitted Creating the chat clientCreating the chat client entails developing the user interface for the chat application which allows users to interact with the server Here are the steps involved in this procedure The first step is to write the client side JavaScript code that will connect to the server via Socket io This entails integrating the Socket io client library in your HTML code and establishing a new Socket io client instance lt script src socket io socket io js gt lt script gt lt script gt const socket io lt script gt Join a chat room To join a chat room you send a “joinRoom event to the server with the desired room ID on receiving this event the server adds the user to the specified room and emit a “userJoined event to other clients in that same room socket emit joinRoom roomId Send messages To send a message listen for the “submit event on the message input form and emit a “sendMessage event to the server on receiving the “sendMessage event the server will disseminate the message to other users in the same room using the “newMessage event const messageForm document querySelector message form messageForm addEventListener submit event gt event preventDefault const messageInput document querySelector message input const message text messageInput value socket emit sendMessage message messageInput value Receive messages In order to receive messages from other users listen for the “newMessage event on the client side and update the UI accordingly socket on newMessage message gt const messagesList document querySelector messages list const messageItem document createElement li messageItem textContent message userId message text messagesList appendChild messageItem This code above makes an entire list item element for each message and adds it to the chat window Handle errors and edge cases Lastly handle errors and edge cases in the client side code such as network errors disconnections and invalid input Listen for the “disconnect event on the client side to detect when the server connection is lost and update the UI accordingly socket on disconnect gt Update UI to indicate that the user is disconnected Additionally validate user input before sending it to the server and display error messages if the input is invalid Connecting to the chat server with Socket ioTo establish a client side Socket io connection in a Node js application follow these steps Install the Socket io client library by running this command in your project directory this will download and install Socket io client library in your project npm install socket io clientLoad the Socket io client library in your client side JavaScript code after installing it by including the following line in your HTML file which will load the it from the server lt script src socket io socket io js gt lt script gt After successfully loading the Socket io client library connect to the server by establishing a Socket io client instance and supplying the server URL as shown below const socket io http localhost This will create a new Socket io client instance and attempt to connect to the server at the supplied URL Emit events to the server using the socket object Once a connection is established with the server For example you can emit a “joinRoom event to the server to join a chat room socket emit joinRoom roomId Here roomId is a variable that contains the ID of the chat room you want to join Listen for events from the server using the socket object To get new chat messages from the server we listen for a “newMessage event here socket on newMessage message gt console log Received message message text Here message is a variable that contains the new chat message received from the server Creating event listeners for incoming socket eventsTo create event listeners for incoming socket events in a Node js chat application you will need to use the socket on method both on the server side and on the client side Create a server side listener for incoming events To receive new chat messages from the client for example listen for a “chatMessage event as seen in the following code socket on chatMessage message gt console log Received message message text Send the message to other users socket broadcast to message room emit newMessage message Here socket refers to the incoming socket connection and message is a variable containing the new chat message received from the client The console log statement simply logs the incoming message to the server console The socket broadcast to message room emit method is used to broadcast the message to all other clients in the same chat room Listen for the identical “newMessage event that the server emitted in response to the incoming “chatMessage event on the client side as illustrated in this code socket on newMessage message gt console log Received message message text Update the UI with the new message displayMessage message Here socket refers to the client side socket connection and message is a variable that contains the new chat message received from the server the console log statement logs the incoming message to the client console while the displayMessage function is a custom function that displays the new message in the UI To send events from the client to the server use the socket emit method To send a new chat message to the server from the client for example emit a “chatMessage event containing the message data as illustrated in this code socket emit chatMessage text messageText room roomId Here socket refers to the client side socket connection and messageText is the text of the new chat message roomId is the ID of the chat room where the message should be sent Developing a User Interface for chat functionalityHere are some steps to get started Make a basic HTML layout for your chat application This should feature a header a chat room display area a message input box and a list of online users To structure your layout you employ semantic HTML tags such as header main section ul and li Make your HTML layout more visually appealing by including CSS styles Use CSS properties like background color border padding font size and text align to customize the appearance of your chat UI Use JavaScript to connect to the chat server using Socket io Use the io function to create a new socket connection in your client side JavaScript code Create event listeners to handle incoming socket events For example to receive new chat messages from the server listen for the “newMessage event and update the UI accordingly You can also listen for the “userList event to receive a list of online users and update the UI with it Use JavaScript to refresh the UI with new chat messages and user online status Also use DOM manipulation methods like document createElement element appendChild and element innerHTML to dynamically create and update HTML elements in response to incoming socket events Finally style the chat messages and online user list using CSS CSS classes and selectors can also be used for adding styles to particular components within the HTML layout Here s an example of how you can display incoming chat messages in your chat UI function displayMessage message const messageContainer document querySelector message container const messageElement document createElement div messageElement classList add message messageElement innerHTML lt span class username gt message username lt span gt message text messageContainer appendChild messageElement Here message is a variable that contains the new chat message received from the server The displayMessage function adds the message text to a new div element with the class “message and appends it to the messageContainer element in the HTML layout Similarly here s an example of how you can update the online user list in the chat s UI function updateUserList users const userList document querySelector user list userList innerHTML users forEach user gt const userElement document createElement li userElement textContent user username userList appendChild userElement Here users is a variable that holds the most recent list of online users received from the server The updateUserList function clears the HTML layout s existing user list loops through the users array generates a new li element for each user and appends it to the userList element Adding new chat functionalitiesWe make use Socket io s built in features and add some custom logic to both client and server code to provide additional chat features such as private messaging message history and notifications Here are a couple of such examples Private messaging To enable private messaging we create a new event on the server called private message which takes in a message and a recipient While on the client side create a form for sending private messages that sends a private message event to the server along with the message and the recipient Server side codesocket on private message function msg recipient Send a private message to the recipient Client side codeconst recipient user const message Good Morning socket emit private message message recipient Displaying message history Create a new event on the server to display message history called chat history which sends the chat history to the client when it connects On the client side create a function that listens for the chat history event and updates the chat UI with the previous messages Server side codesocket on connection function Send chat history to the connected client socket emit chat history chatHistory Client side codesocket on chat history function history Update chat UI with message history Enable Notifications Create a new event to send notifications on the server called notification that delivers a notification message to all connected clients While on the client side create a function that listens for the notification event and displays a notification message to the user Server side codefunction sendNotification message Push notification to all clients io emit notification message Client side codesocket on notification function message Display notification message to the user By implementing these additional chat features we can make our real time chat application more useful and user friendly Using Giphy to enhance the conversation experienceExternal APIs such as Giphy adds more fun and interactivity to the chat experience Here s an example of how we can integrate Giphy API into our chat application First we obtain an API key from Giphy by signing up for their developer program Then we use a library like axios to make HTTP requests to the Giphy API and fetch GIFs based on user input const apiKey your api key here const apiUrl apiKey function searchGifs query return fetch apiUrl amp q query then response gt response json then data gt const gifUrls data data map gif gt gif images original url return gifUrls On the client side we provide an input field where users search for GIFs and send a message with the selected GIF to the chat lt HTML code for the input field → lt input type text id gif search placeholder Search for a GIF gt lt button id gif search btn gt Search lt button gt Client side code for searching and sending GIFsconst searchInput document getElementById gif search const searchBtn document getElementById gif search btn searchBtn addEventListener click function const query searchInput value searchGifs query then gifUrls gt Select a GIF from the results const gifUrl gifUrls Math floor Math random gifUrls length Send a message with the GIF to the chat const message lt img src gifUrl alt GIF gt socket emit chat message message catch error gt console error error By integrating Giphy API or other external APIs we add more engaging features to our chat application making it significantly more appealing and interactive for users ConclusionIn conclusion a real time chat application is an online application that allows users to effectively communicate with each other in real time using technologies such as Node js Express js and Socket io through text messages Building a real time chat application may be a fun and dynamic way for users to converse while also learning and practicing web development skills To create a real time chat application we must first set up the server using Express js then configure Socket io on the server create event listeners for incoming socket connections implement basic chat functionality with socket events handle edge cases create the chat client and implement additional chat features such as private messaging message history and external APIs such as Giphy 2023-04-30 19:33:43
海外科学 NYT > Science As Hospitals Close and Doctors Flee, Sudan’s Health Care System Is Collapsing https://www.nytimes.com/2023/04/30/world/africa/sudan-hospitals-doctors-fighting.html As Hospitals Close and Doctors Flee Sudan s Health Care System Is CollapsingThe medical professionals who remain face meager supplies and harrowing conditions even setting up field hospitals in living rooms amid the fighting 2023-04-30 19:18:38
医療系 医療介護 CBnews DPC/PDPS カバー率の定義を変えてはどうか-先が見えない時代の戦略的病院経営(195) https://www.cbnews.jp/news/entry/20230428130359 dpcpdps 2023-05-01 05:00:00
ニュース BBC News - Home Nurses' strike: 28-hour strike over pay under way https://www.bbc.co.uk/news/health-65443943?at_medium=RSS&at_campaign=KARANGA action 2023-04-30 19:23:29
ニュース BBC News - Home Terrorists limited to two boxes of books in prison cells https://www.bbc.co.uk/news/uk-65443483?at_medium=RSS&at_campaign=KARANGA religious 2023-04-30 19:35:18
ニュース BBC News - Home I don't know what Tierney has against us - Klopp questions referee https://www.bbc.co.uk/sport/football/65443810?at_medium=RSS&at_campaign=KARANGA I don x t know what Tierney has against us Klopp questions refereeLiverpool boss Jurgen Klopp says referee Paul Tierney appears to have something against his team after their win over Tottenham 2023-04-30 19:48:03
ビジネス ダイヤモンド・オンライン - 新着記事 シン富裕層が台頭、富裕層の「投資・節税・相続」事情も激変!億万長者の知恵を公開 - シン富裕層の投資・節税・相続 https://diamond.jp/articles/-/321952 シン富裕層が台頭、富裕層の「投資・節税・相続」事情も激変億万長者の知恵を公開シン富裕層の投資・節税・相続従来の富裕層とは異なる、新たな志向やビジネスモデルを持った「シン富裕層」が日本で台頭している。 2023-05-01 04:50:00
ビジネス ダイヤモンド・オンライン - 新着記事 注目テーマ株の勝者・敗者は?AI、インバウンド、半導体…バフェットも熱視線の日本株を大分析 - 注目テーマをメッタ斬り! “人気株”の勝者・敗者 https://diamond.jp/articles/-/322194 浮き彫り 2023-05-01 04:45:00
ビジネス ダイヤモンド・オンライン - 新着記事 【無料公開】婚礼最大手テイクアンドギヴ・ニーズと「ゼクシィ」が対立に向かう意外な理由 - Diamond Premiumセレクション https://diamond.jp/articles/-/322361 diamond 2023-05-01 04:40:00
ビジネス ダイヤモンド・オンライン - 新着記事 大企業主導から中堅企業主導へ、多様化する「新しい」中小企業再編とは - 企業サバイバル最前線 https://diamond.jp/articles/-/321174 中堅企業 2023-05-01 04:35:00
ビジネス ダイヤモンド・オンライン - 新着記事 FRBが5月の0.25%で「利上げ打ち止め」の見通し、軟着陸シナリオの成算 - 政策・マーケットラボ https://diamond.jp/articles/-/322317 不動産市場 2023-05-01 04:30:00
ビジネス ダイヤモンド・オンライン - 新着記事 中国による世界経済回復は“期待外れ”、米中覇権争いで注目の「輸入力」とは - 政策・マーケットラボ https://diamond.jp/articles/-/322352 中国による世界経済回復は“期待外れ、米中覇権争いで注目の「輸入力」とは政策・マーケットラボ中国の景気回復は、先進国が利上げや金融不安で苦しむ中、世界経済を支える救世主として期待が高まっている。 2023-05-01 04:25:00
ビジネス ダイヤモンド・オンライン - 新着記事 【東大和市ベスト3】小学校区「教育環境力」ランキング!【偏差値チャート最新版】 - 東京・小学校区「教育環境力」ランキング2022 https://diamond.jp/articles/-/322387 【東大和市ベスト】小学校区「教育環境力」ランキング【偏差値チャート最新版】東京・小学校区「教育環境力」ランキング子どもにとってよりよい教育環境を目指し、入学前に引っ越して小学校区を選ぶ時代になった。 2023-05-01 04:20:00
ビジネス ダイヤモンド・オンライン - 新着記事 「会社がホワイト過ぎて成長できない」と嘆く人が、転職してはいけない理由 - 転職で幸せになる人、不幸になる人 丸山貴宏 https://diamond.jp/articles/-/322316 働き方改革 2023-05-01 04:15:00
ビジネス ダイヤモンド・オンライン - 新着記事 「しんどい」はあなたが頑張ってきた証、心をほぐず人気カウンセラーの言葉 - 要約の達人 from flier https://diamond.jp/articles/-/322035 「しんどい」はあなたが頑張ってきた証、心をほぐず人気カウンセラーの言葉要約の達人fromflier「しんどい」という感情を持つ状態は、「サボっているわけでも、怠けているわけでも、やる気がないわけでも、甘えているわけでも、逃げているわけでもありません」と著者は断言する。 2023-05-01 04:10:00
ビジネス ダイヤモンド・オンライン - 新着記事 年収が高い会社ランキング2022最新版【平均年齢30代・従業員100人未満】トップ5、1位は1694万円! - ニッポンなんでもランキング! https://diamond.jp/articles/-/322364 年収が高い会社ランキング最新版【平均年齢代・従業員人未満】トップ、位は万円ニッポンなんでもランキングダイヤモンド編集部の名物企画である「年収ランキング」は、これまで、さまざまな切り口でランキングを作成してきた。 2023-05-01 04:05:00
ビジネス ダイヤモンド・オンライン - 新着記事 年収が高い会社ランキング2022最新版【平均年齢30代・従業員100人未満】全200社完全版 - ニッポンなんでもランキング! https://diamond.jp/articles/-/322315 年収が高い会社ランキング最新版【平均年齢代・従業員人未満】全社完全版ニッポンなんでもランキングダイヤモンド編集部の名物企画である「年収ランキング」は、これまで、さまざまな切り口でランキングを作成してきた。 2023-05-01 04:05:00
ビジネス 東洋経済オンライン 「評価者思考」の管理職が成果を出せない納得理由 質の高いアウトプットを生むリーダーの思考法 | リーダーシップ・教養・資格・スキル | 東洋経済オンライン https://toyokeizai.net/articles/-/665596?utm_source=rss&utm_medium=http&utm_campaign=link_back 東洋経済オンライン 2023-05-01 04:50:00
ビジネス 東洋経済オンライン 新幹線「新横浜駅」時刻表が物語る地位向上の歴史 開業以来の「停車本数」変遷を調査してわかった | 新幹線 | 東洋経済オンライン https://toyokeizai.net/articles/-/668535?utm_source=rss&utm_medium=http&utm_campaign=link_back 新横浜線 2023-05-01 04:20:00
海外TECH reddit [Post Game Thread] The Miami Heat (1-0) continue their hot streak and defeat the New York Knicks (0-1) in Game 1 at MSG, 108-101. Jimmy Butler scores 25 PTS. https://www.reddit.com/r/nba/comments/1340swl/post_game_thread_the_miami_heat_10_continue_their/ Post Game Thread The Miami Heat continue their hot streak and defeat the New York Knicks in Game at MSG Jimmy Butler scores PTS Box Scores NBA Yahoo nbsp GAME SUMMARY Location Madison Square Garden Clock Final Officials Tony Brothers Bill Kennedy and Brent Barnaky Team Q Q Q Q Total Miami Heat New York Knicks nbsp TEAM STATS Team PTS FG FG P P FT FT OREB TREB AST PF STL TO BLK Miami Heat New York Knicks nbsp PLAYER STATS Miami Heat MIN PTS FGM A PM A FTM A ORB DRB REB AST STL BLK TO PF ± Jimmy ButlerSF Kevin LovePF Bam AdebayoC Max StrusSG Gabe VincentPG Caleb Martin Kyle Lowry Duncan Robinson Haywood Highsmith Cody Zeller Udonis Haslem Nikola Jovic Omer Yurtseven Tyler Herro Victor Oladipo New York Knicks MIN PTS FGM A PM A FTM A ORB DRB REB AST STL BLK TO PF ± RJ BarrettSF Obi ToppinPF Mitchell RobinsonC Jalen BrunsonSG Josh HartPG Isaiah Hartenstein Immanuel Quickley Quentin Grimes Evan Fournier DaQuan Jeffries Miles McBride Julius Randle Derrick Rose Jericho Sims rnbapgtgenerator by u fukr submitted by u IamOlderthanMe to r nba link comments 2023-04-30 19:33:33

コメント

このブログの人気の投稿

投稿時間:2021-06-17 22:08:45 RSSフィード2021-06-17 22:00 分まとめ(2089件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)