Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to create a WebSocket server

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to create a WebSocket server". In daily operation, I believe many people have doubts about how to create a WebSocket server. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to create a WebSocket server"! Next, please follow the editor to study!

Before we begin, let's take a look at what we want to achieve today:

All right, no more nonsense, let's come in and see how this thing is going to be realized.

Create a Web project

Here, as above (WebSocket (2)), after the web project is successfully created, we still have to manually add the jar package of websocket.

Create a HTML page

The effect of the page has been seen by my friends just now, so I will go directly to the code here:

Ws page var webSocket; $("# btnClick2") .click (function () {var msg = $("# msg"). Val (); $("# msg"). Val ('); webSocket.send (msg)}); $("# btnClick1") .click (function () {var nickname = $("# nickname"). Val () If (nickname==null | | nickname=='') {alert ("must enter a nickname"); return;} $("# btnClick2"). RemoveAttr ("disabled"); $(this) .attr ("disabled", "disabled"); $("# resultDiv") .append ("

Start connecting to the server!

"); webSocket = new WebSocket (" ws://localhost/myws2/ "+ nickname); webSocket.onerror = function (event) {$(" # resultDiv ") .append ("

Onerror: "+ event.data +"

);} webSocket.onopen = function (event) {$("# resultDiv") .append ("

Connection successful!

);} webSocket.onmessage = function (event) {$("# resultDiv") .append ("

"+ event.data +"

");})

With regard to this HTML code, I would like to say the following:

1. The send button is not available at first and must be connected first

two。 You must first enter a nickname when connecting. If you do not enter a nickname, a prompt will pop up.

3. After a successful connection, the connection button is unclickable and the send button is clickable.

4. Initialize the WebSocket object and some of the methods involved in WebSocket in the click event of the connection button

5. All the information (connection success, connection error, and message received) is finally displayed in resultDiv

6. The connection address is dynamic, and the last character is the user name of the connection.

Create a WebSocket server

Since what we are going to do here is group chat, the main function of the server is to receive the message from the client and broadcast it to all clients. The server code is as follows:

@ ServerEndpoint ("/ myws2/ {nickname}") public class WebSocketServer2 {private String nickname; private Session session; private static final Set WEB_SOCKET_SERVER_2_SET = new CopyOnWriteArraySet (); @ OnMessage public void onMessage (String message, @ PathParam (value = "nickname") String nickname) throws IOException {System.out.println ("received a message from the client:" + message); sendText (nickname+ "sent:" + message) } private static void sendText (String msg) {for (WebSocketServer2 webSocketServer2: WEB_SOCKET_SERVER_2_SET) {try {synchronized (webSocketServer2) {webSocketServer2.session.getBasicRemote () .sendText (msg);}} catch (IOException e) {WEB_SOCKET_SERVER_2_SET.remove (webSocketServer2) Try {webSocketServer2.session.close ();} catch (IOException E1) {} sendText (webSocketServer2.nickname + "classmate has been offline");}} @ OnOpen public void onOpen (Session session, @ PathParam (value = "nickname") String nickname) throws IOException {this.nickname = nickname This.session = session; WEB_SOCKET_SERVER_2_SET.add (this); sendText (nickname + "enter the room"); StringBuffer sb = new StringBuffer (); for (WebSocketServer2 webSocketServer2: WEB_SOCKET_SERVER_2_SET) {sb.append (webSocketServer2.nickname) .append (";");} sendText ("current room has:" + sb.toString ()) @ OnClose public void onClose (Session session) throws IOException {WEB_SOCKET_SERVER_2_SET.remove (this); sendText (this.nickname+ "Children's shoes are offline");}}

I would like to explain the following points about this server:

1. The first line of code represents the name of the server, but there is a {nickname} in the name to get the last parameter passed by the server, which can be obtained in the method through @ PathParam, which is the same as the parameter annotation of SpringMVC.

two。 The third and fourth lines create two objects, because after the client faces the server, a client will correspond to a WebSocketServer2 object. I need to save the information about each client, so create a nickname to represent the user nickname of the client corresponding to the object, and session to represent the session of the client corresponding to the object.

3. The fifth line creates a Set collection, which is of type static final, indicating that no matter how many objects there are in WebSocketServer2, the WEB_SOCKET_SERVER_2_SET collection is always the same, which is mainly used to hold the WebSocketServer2 objects corresponding to all connected clients.

4. Lines 30 to 41 are the logic of the open method, which has two parameters, the first session and the second nickname,nickname parameter with an annotation @ PathParam indicating that the value of this parameter is the last string in the concatenation address, which is optional. In this method, we first assign nickname and session to the corresponding global variables, then add the current object to the set collection, and then call the sendText method to send a message telling all clients that XXX has entered the room. Finally, we iterate through all the users in the set collection, get the user names of all users, and then tell all clients who is in the current room.

5. The sendText method in lines 13-28 is a custom static method, which is mainly used to broadcast messages to all clients. The basic logic of this method is to traverse the set collection, get each object in the set collection and the session in each object, and then use session to send a message to the corresponding client. If the message fails, the user is removed from the collection. At the same time, tell the remaining clients that so-and-so has gone offline.

6. The code in lines 7-10 is mainly used to process messages sent by the client. The default parameters of String type represent the messages sent by the client, and other parameters of String type need to be annotated. Here, the first parameter represents the message sent by the client, and the second parameter represents the nickname of the user who sent the client message. After receiving the message, it is broadcast to all users using sendText.

7. Lines 43 to 47 indicate that when one of the users goes offline, the close method will be called back, in which the corresponding WebSocketServer2 object of the client is first removed from the collection, and then a message is broadcast to tell everyone about the user's offline.

At this point, the study on "how to create a WebSocket server" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report