您现在的位置是:首页 >技术交流 >WSL2和Windows之间通信实现【以Unity为例】网站首页技术交流

WSL2和Windows之间通信实现【以Unity为例】

cycler_725 2023-06-15 08:00:02
简介WSL2和Windows之间通信实现【以Unity为例】


WSL2可以视为一个独立的虚拟机,具有自己独立的IP地址,通过虚拟路由器与Windows连接,因此WSL2不能直接访问到Windows的主机地址,需要动态获取。

(1)Windows启用防火墙的WSL2的访问

默认情况下Windows的防火墙会阻止WSL2中应用对Windows的网络访问(see: Add "allow" rule to Windows firewall for WSL2 network · Issue #4585 · microsoft/WSL (github.com)),解决办法是添加一条防火墙规则允许WSL2对Windows的访问。请以管理员身份打开PowerShell并键入以下命令:

PS C:> New-NetFirewallRule -DisplayName "WSL" -Direction Inbound  -InterfaceAlias "vEthernet (WSL)"  -Action Allow

查看防火墙的高级设置中的入站规则:

其实也可以直接关闭所有防火墙。

(2)WSL2获取Windows的IP地址并建立连接

由于Windows相对WSL2的IP会发生变化,我们需要每次启动前先获取这个IP来保证顺利访问

import numpy as np
import socket
import os

def connect_unity(host,port):
    global sock
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((host, port))
    print('连接已建立')

import subprocess
cmd_get_ip = 'grep -oP  "(d+.)+(d+)" /etc/resolv.conf'
host = subprocess.run(
        cmd_get_ip, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True
        ).stdout.strip() # 获取windows的IP
 
port = 5005        # Unity监听的端口号

connect_unity(host,port)

WSL2的IP Address:

$ip a |grep "global eth0"

输出得到:

WSL2的IP地址就是:172.18.119.46

(3)使用Unity监听和连接

使用了0.0.0.0进行监听,相当于监听本机上所有的IP地址

public class U2P
{  
    private U2P()
    {
        serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPAddress ipAddress = IPAddress.Parse("0.0.0.0");
        serverSocket.Bind(new IPEndPoint(ipAddress, 5005));
        serverSocket.Listen(5); 
        StartServer();
    }
    private void StartServer()
    {
        serverSocket.BeginAccept(AcceptCallback, null);
    }
    private void AcceptCallback(IAsyncResult ar)
    {
        Socket sc = serverSocket.EndAccept(ar); 
        if (clientSocket == null)
        {
            clientSocket = sc; 
            isConnected = true;
            Debug.Log("连接成功");
        }
    }
public float[] RecData()
    {
        try
        {
            if (clientSocket != null)
            {
                int canRead = clientSocket.Available;
                byte[] buff = new byte[canRead];
                clientSocket.Receive(buff);
                string str = Encoding.UTF8.GetString(buff);
                //Debug.Log(str);
                if (str == "")
                {
                    return null;
                }
                //str = str.Replace("[","").Replace("]","").Replace("
")Replace("Replace(
                //Debug.Log(“接受消息:”+ str);
                string[] strData = str.Split(',');
                float[] data = new float[strData.Length];
                for (int i = 0; i < strData.Length; i++)
                {
                    data[i] = float.Parse(strData[i]);
                }
                //Debug.Log("数据:"+data[7]);
                return data;
            }
        }
        catch (Exception ex)
        {
            Debug.LogError("发生错误:"+ex);
            if (clientSocket != null)
            {
                clientSocket.Close(); 
                clientSocket = null; 
                isConnected = false;
                StartServer();
            }
        }
        return null;
    }
    public void SendData(List<float> data)
    {
        try
        {
            if (clientSocket != null)
            {
                string strData = "";
                for (int i = 0; i < data.Count; i++)
                {
                    strData += data[i];
                    if (i != data.Count - 1)
                    {
                        strData += ",";
                    }
                }
                // 请补充使用UTF8编码,使用clientSocket发送strData到服务器的代码
                byte[] dataBytes = Encoding.UTF8.GetBytes(strData);
                clientSocket.Send(dataBytes);
            }
        }
        catch (Exception ex)
        {
            //Debug.LogError("发生错误:”+ex);
            if (clientSocket != null)
            {
                clientSocket.Close();
                clientSocket = null;
                isConnected = false;
                StartServer();
            }
        }
    }
}

参考:

https://mp.csdn.net/mp_blog/creation/editor?spm=1000.2115.3001.5352

风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。