Implementation of communication between WSL2 and Windows [Take Unity as an example]


WSL2 can be regarded as an independent virtual machine with its own independent IP address. It is connected to Windows through a virtual router. Therefore, WSL2 cannot directly access the Windows host address and needs to obtain it dynamically.

(1) Windows firewall enabled WSL2 access

By default, Windows firewall blocks WSL2 applications from accessing the Windows network (see: Add "allow" rule to Windows firewall for WSL2 network · Issue #4585 · microsoft/WSL (github.com) ) . The solution is to add a Firewall rules allow WSL2 access to Windows. Please open PowerShell as administrator and type the following command:

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

View the inbound rules in the firewall's advanced settings:

In fact, you can also turn off all firewalls directly.

(2) WSL2 obtains the IP address of Windows and establishes a connection

Since the IP of Windows will change relative to WSL2, we need to obtain this IP before each startup to ensure smooth access.

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"

The output is:

The IP address of WSL2 is: 172.18.119.46

(3) Use Unity to monitor and connect

0.0.0.0 is used for monitoring, which is equivalent to monitoring all IP addresses on this machine.

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("\n")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();
            }
        }
    }
}

reference:

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

Guess you like

Origin blog.csdn.net/cycler_725/article/details/130374433
Recommended