Real-time communication between WeChat applet and Unity3d

1. This time, a case of making a small program to send a message to the Unity3d interactive large screen display according to the demand, the first effect:

Applet Unity

2. Use SpringBoot to write a Socket communication, which is used to monitor the connection of the unity3d client and forward the message to unity3d:

code show as below:

public class SocketIOServiceImpl implements ISocketIOService{
    /**
     * 存放已连接的客户端
     */
    private static Map<String, SocketIOClient> clientMap = new ConcurrentHashMap<>();

    /**
     * 自定义事件`push_data_event`,用于服务端与客户端通信
     */
    private static final String PUSH_DATA_EVENT = "push_data_event";

    @Autowired
    private SocketIOServer socketIOServer;

    /**
     * Spring IoC容器创建之后,在加载SocketIOServiceImpl Bean之后启动
     */
    @PostConstruct
    private void autoStartup() {
        start();
    }

    @PreDestroy
    private void autoStop() {
        stop();
    }

    @Override
    public void start() {
        // 监听客户端连接
        socketIOServer.addConnectListener(client -> {
            System.out.println("************ 客户端: " + getIpByClient(client) + " 已连接 ************");
            // 自定义事件`connected` -> 与客户端通信  (也可以使用内置事件,如:Socket.EVENT_CONNECT)
            client.sendEvent("connected", "你成功连接上了哦...");
            String userId = getParamsByClient(client);
            System.out.println(userId);
            if (userId != null) {
                clientMap.put(userId, client);
            }
        });

        // 监听客户端断开连接
        socketIOServer.addDisconnectListener(client -> {
            String clientIp = getIpByClient(client);
            System.out.println(clientIp + " *********************** " + "客户端已断开连接");
            client.sendEvent("disconnect", "你成功断开连接了哦...");
            String userId = getParamsByClient(client);
            if (userId != null) {
                clientMap.remove(userId);
                client.disconnect();
            }
        });

        // 自定义事件`client_info_event` -> 监听客户端消息
        socketIOServer.addEventListener(PUSH_DATA_EVENT, String.class, (client, data, ackSender) -> {
            // 客户端推送`client_info_event`事件时,onData接受数据,这里是string类型的json数据,还可以为Byte[],object其他类型
            String clientIp = getIpByClient(client);
            System.out.println(clientIp + " ************ 客户端:" + data);
            socketIOServer.getNamespace("").getBroadcastOperations().sendEvent(PUSH_DATA_EVENT,data);
        });

        // 启动服务
        socketIOServer.start();
    }

    @Override
    public void stop() {
        if (socketIOServer != null) {
            socketIOServer.stop();
            socketIOServer = null;
        }
    }

    @Override
    public void pushMessageToUser(String userId, String msgContent) {
        SocketIOClient client = clientMap.get(userId);
        if (client != null) {
            client.sendEvent(PUSH_DATA_EVENT, msgContent);
        }
    }

3. Write a Socket connection server in unity3d, open a socket thread to receive the small program message forwarded by the server in real time, (IP, port number)

var uri = new Uri("http://127.0.0.1:8888");
        SocketIOUnity socket = new SocketIOUnity(uri, new SocketIOOptions
        {
            Query = new Dictionary<string, string>
        {
            {"token", "UNITY" }
        }
            ,
            Transport = SocketIOClient.Transport.TransportProtocol.WebSocket
        });

        socket.JsonSerializer = new NewtonsoftJsonSerializer();
        socket.On("connected", (response) =>
        {
            var obj = response.GetValue<string>();
            msg = obj;
            Debug.Log(obj);
        });
        socket.On("push_data_event", (response) =>
        {
            var obj = response.GetValue<string>();
            //Debug.Log(obj);
            msg = obj;
            resMsg = true;
        });
        socket.Connect();

4. After the server and unity3d complete the communication, write an interface for the applet in springboot, which is used for the applet to pass messages and call:

import com.mo.serverdemo.service.SocketIOServiceImpl;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/unity")
public class MessageToUnityController {

    @Autowired
    private SocketIOServiceImpl socketIOService;


    @GetMapping("/send")
    public String forwardMessage(@RequestParam("message") String message) {
        socketIOService.brocastMessage(message);
        return "ok";
    }
}

5. The applet calls this interface to transmit messages:

 6. Real-time messages can be sent and received after the call is successful.

Guess you like

Origin blog.csdn.net/m0_38116456/article/details/131719071