websokcet服务端实现

本文详细介绍了如何在SpringBoot项目中利用WebSocket进行服务端的配置和客户端的HTML5及后台Java实现,包括依赖引入、Bean配置、服务器端核心代码和客户端连接示例。
摘要由CSDN通过智能技术生成

一/websokcet服务端实现

步骤一: springboot底层帮我们自动配置了websokcet,引入maven依赖

1

2

3

4

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-websocket</artifactId>

</dependency>

步骤二:如果是你采用springboot内置容器启动项目的,则需要配置一个Bean。如果是采用外部的容器,则可以不需要配置。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

/**

 * @Description: 配置类

 */

@Component

public class WebSocketConfig {

  

    /**

     * ServerEndpointExporter 作用

     *

     * 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint

     *

     * @return

     */

    @Bean

    public ServerEndpointExporter serverEndpointExporter() {

        return new ServerEndpointExporter();

    }

}

 步骤三:最后一步当然是编写服务端核心代码了,其实本人不是特别想贴代码出来,贴很多代码影响文章可读性。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

package com.example.socket.code;

  

import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Component;

  

import javax.websocket.OnClose;

import javax.websocket.OnMessage;

import javax.websocket.OnOpen;

import javax.websocket.Session;

import javax.websocket.server.PathParam;

import javax.websocket.server.ServerEndpoint;

import java.util.concurrent.ConcurrentHashMap;

  

/**

 * @Description: websocket 服务类

 */

  

/**

 *

 * @ServerEndpoint 这个注解有什么作用?

 *

 * 这个注解用于标识作用在类上,它的主要功能是把当前类标识成一个WebSocket的服务端

 * 注解的值用户客户端连接访问的URL地址

 *

 */

  

@Slf4j

@Component

@ServerEndpoint("/websocket/{name}")

public class WebSocket {

  

    /**

     *  与某个客户端的连接对话,需要通过它来给客户端发送消息

     */

    private Session session;

  

     /**

     * 标识当前连接客户端的用户名

     */

    private String name;

  

    /**

     *  用于存所有的连接服务的客户端,这个对象存储是安全的

     */

    private static ConcurrentHashMap<String,WebSocket> webSocketSet = new ConcurrentHashMap<>();

  

  

    @OnOpen

    public void OnOpen(Session session, @PathParam(value = "name") String name){

        this.session = session;

        this.name = name;

        // name是用来表示唯一客户端,如果需要指定发送,需要指定发送通过name来区分

        webSocketSet.put(name,this);

        log.info("[WebSocket] 连接成功,当前连接人数为:={}",webSocketSet.size());

    }

  

  

    @OnClose

    public void OnClose(){

        webSocketSet.remove(this.name);

        log.info("[WebSocket] 退出成功,当前连接人数为:={}",webSocketSet.size());

    }

  

    @OnMessage

    public void OnMessage(String message){

        log.info("[WebSocket] 收到消息:{}",message);

        //判断是否需要指定发送,具体规则自定义

        if(message.indexOf("TOUSER") == 0){

            String name = message.substring(message.indexOf("TOUSER")+6,message.indexOf(";"));

            AppointSending(name,message.substring(message.indexOf(";")+1,message.length()));

        }else{

            GroupSending(message);

        }

  

    }

  

    /**

     * 群发

     * @param message

     */

    public void GroupSending(String message){

        for (String name : webSocketSet.keySet()){

            try {

                webSocketSet.get(name).session.getBasicRemote().sendText(message);

            }catch (Exception e){

                e.printStackTrace();

            }

        }

    }

  

    /**

     * 指定发送

     * @param name

     * @param message

     */

    public void AppointSending(String name,String message){

        try {

            webSocketSet.get(name).session.getBasicRemote().sendText(message);

        }catch (Exception e){

            e.printStackTrace();

        }

    }

}

二、客户端实现

HTML5实现:以下就是核心代码了,其实其他博客有很多,本人就不多说了。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

var websocket = null;

   if('WebSocket' in window){

       websocket = new WebSocket("ws://192.168.2.107:8085/websocket/testname");

   }

   websocket.onopen = function(){

       console.log("连接成功");

   }

   websocket.onclose = function(){

       console.log("退出连接");

   }

   websocket.onmessage = function (event){

       console.log("收到消息"+event.data);

   }

   websocket.onerror = function(){

       console.log("连接出错");

   }

   window.onbeforeunload = function () {

       websocket.close(num);

   }

SpringBoot后台实现:本人发现多数博客都是采用js来实现客户端,很少有用后台来实现,所以本人也就写了写,大神请勿喷?。很多时候,项目与项目之间通讯也需要后台作为客户端来连接。

步骤一:首先我们要导入后台连接websocket的客户端依赖

1

2

3

4

5

6

<!--websocket作为客户端-->

<dependency>

    <groupId>org.java-websocket</groupId>

    <artifactId>Java-WebSocket</artifactId>

    <version>1.3.5</version>

</dependency>

 步骤二:把客户端需要配置到springboot容器里面去,以便程序调用。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

package com.example.socket.config;

  

import lombok.extern.slf4j.Slf4j;

import org.java_websocket.client.WebSocketClient;

import org.java_websocket.drafts.Draft_6455;

import org.java_websocket.handshake.ServerHandshake;

import org.springframework.context.annotation.Bean;

import org.springframework.stereotype.Component;

  

import java.net.URI;

  

/**

 * @Description: 配置websocket后台客户端

 */

@Slf4j

@Component

public class WebSocketConfig {

  

    @Bean

    public WebSocketClient webSocketClient() {

        try {

            WebSocketClient webSocketClient = new WebSocketClient(new URI("ws://localhost:8085/websocket/test"),new Draft_6455()) {

                @Override

                public void onOpen(ServerHandshake handshakedata) {

                    log.info("[websocket] 连接成功");

                }

  

                @Override

                public void onMessage(String message) {

                    log.info("[websocket] 收到消息={}",message);

  

                }

  

                @Override

                public void onClose(int code, String reason, boolean remote) {

                    log.info("[websocket] 退出连接");

                }

  

                @Override

                public void onError(Exception ex) {

                    log.info("[websocket] 连接错误={}",ex.getMessage());

                }

            };

            webSocketClient.connect();

            return webSocketClient;

        catch (Exception e) {

            e.printStackTrace();

        }

        return null;

    }

  

}

步骤三:使用后台客户端发送消息

1、首先本人写了一个接口,里面有指定发送和群发消息两个方法。

2、实现发送的接口,区分指定发送和群发由服务端来决定(本人在服务端写了,如果带有TOUSER标识的,则代表需要指定发送给某个websocket客户端)。

3、最后采用get方式用浏览器请求,也能正常发送消息。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

package com.example.socket.code;

  

/**

 * @Description: websocket 接口

 */

public interface WebSocketService {

  

    /**

     * 群发

     * @param message

     */

     void groupSending(String message);

  

    /**

     * 指定发送

     * @param name

     * @param message

     */

     void appointSending(String name,String message);

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

package com.example.socket.chat;

  

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

  

/**

 * @Description: 测试后台websocket客户端

 */

@RestController

@RequestMapping("/websocket")

public class IndexController {

  

    @Autowired

    private WebSocketService webSocketClient;

  

    @GetMapping("/sendMessage")

    public String sendMessage(String message){

        webScoketClient.groupSending(message);

        return message;

    }

}

三、最后

注意:

如果是单例的情况下,这个对象的值都会被修改。

本人就抽了时间Debug了一下,经过下图也可以反映出,能够看出,webSokcetSet中存在三个成员,并且vlaue值都是不同的,所以在这里没有出现对象改变而把之前对象改变的现象。

服务端这样写是没问题的。

最后总结:在实际WebSocket服务端案例中为什么没有出现这种情况,当WebSokcet这个类标识为服务端的时候,每当有新的连接请求,这个类都是不同的对象,并非单例。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

import com.alibaba.fastjson.JSON;

  

import java.util.concurrent.ConcurrentHashMap;

  

/**

 * @Description:

 */

public class TestMain {

  

    /**

     * 用于存所有的连接服务的客户端,这个对象存储是安全的

     */

    private static ConcurrentHashMap<String, Student> webSocketSet = new ConcurrentHashMap<>();

  

    public static void main(String[] args) {

        Student student = Student.getStudent();

        student.name = "张三";

        webSocketSet.put("1", student);

  

        Student students = Student.getStudent();

        students.name = "李四";

        webSocketSet.put("2", students);

  

        System.out.println(JSON.toJSON(webSocketSet));

    }

}

  

/**

 * 提供一个单例类

 */

class Student {

  

    public String name;

  

    private Student() {

    }

  

    private static final Student student = new Student();

  

    public static Student getStudent() {

        return student;

  

    }

}

 打印结果:

1

{"1":{"name":"李四"},"2":{"name":"李四"}}

  • 30
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值