为什么客户端(C#的HoloLens)不能从服务器(python的PC)接收消息?(客户端可以向服务器发送图像。)
以下是客户端(HoloLens)脚本的一部分。我使用ReceiveMessage()接收从服务器发送的数据,但实际上我无法接收任何内容。SendImage(byte[]image)可以将图像从客户端发送到服务器,并且运行良好。为什么?ReceiveMessage()有什么问题吗? 在获取字符串数据(名称形式为python)后,我想使用ReceiveMessage()的结果为要显示在HoloLens上的对象文本赋值。 ''' ''' 下面是名为client的游戏对象的脚本。实现功能的统一是最重要的部分。 ''' ''' 以下是服务器(PC)的部分脚本。我使用clientsock.sendall(name.encode())将name的数据(Python从HoloLens接收图像,然后处理图像以获取图像中的人的姓名)从服务器发送到客户端。 '''为什么客户端(C#的HoloLens)不能从服务器(python的PC)接收消息?(客户端可以向服务器发送图像。),c#,unity3d,hololens,C#,Unity3d,Hololens,以下是客户端(HoloLens)脚本的一部分。我使用ReceiveMessage()接收从服务器发送的数据,但实际上我无法接收任何内容。SendImage(byte[]image)可以将图像从客户端发送到服务器,并且运行良好。为什么?ReceiveMessage()有什么问题吗? 在获取字符串数据(名称形式为python)后,我想使用ReceiveMessage()的结果为要显示在HoloLens上的对象文本赋值。 ''' ''' 下面是名为client的游戏对象的脚本。实现功能的统一是最重要的
“”“有可能在异步任务分配之前调用ReceiveMessage方法。我对代码进行了一些修改,您可以通过编程将其存储在项目中:
public TcpNetworkClientManager(string IP, int port)
{
#if !UNITY_EDITOR
Connect(IP, port);
#endif
}
#if !UNITY_EDITOR
public async void Connect(string IP, int port)
{
try
{
StreamSocket socket = new StreamSocket();
await socket.ConnectAsync(new HostName(IP), port.ToString());
Stream streamOut = socket.OutputStream.AsStreamForWrite();
writer = new StreamWriter(streamOut) { AutoFlush = true };
Stream streamIn = socket.InputStream.AsStreamForRead();
reader = new StreamReader(streamIn);
ReceiveMessage();
}
catch (Exception e)
{
}
}
#endif
看来你发布的运行在HoloLens上的代码应该可以运行了。它应该与网络无关。您能仔细检查一下python脚本中调用的
FaceRec(img)
函数是否返回了有效的名称字符串吗?实际上,如果不使用ReceiveMessage()方法,FaceRec(img)可以很好地工作。我不知道如何在另一个脚本中调用ReceiveMessage()的这个方法。我正在尝试使用message=newtcpnetworkclientmanager(IP,端口),然后将Text=message.ReceiveMessage()放入void update()函数中。这似乎不起作用。它将使整个插座崩溃。非常感谢您的回答。但当我试图将其放入整个脚本中时,我得到了Unity的一个例外“无法使用特性`异步函数',因为它不是C#4.0语言规范的一部分”。unity版本为2017.4.1。我该怎么应付呢?再次感谢你!根据错误消息,它应该将整个异步函数放在条件编译语句体中。我已经在代码中修复了这个问题。如果试用后仍然无法使用,请随时通知我。顺便说一句,对于Unity 2017,支持的最低版本是2017.4.17,您应该使用此版本或更高版本:非常感谢您的精彩脚本!更具体地说,我在问题中添加了另一个名为Client的游戏对象脚本。有两件事需要认识到。1.名为client的游戏对象可以捕获图像并调用方法“SendImage(byte[]image)”将其发送到PC。它可以工作。2.我想得到从PC发回的字符串数据,并将其显示在文本中。但它不起作用。实际上,我不知道如何让名为client的游戏对象调用相应的方法(ReceiveMessage())来让文本显示字符串数据。如果可能的话,你能给我一些建议吗?在我的代码中,它在套接字连接到远程网络后被调用,并且只调用了一次。在代码中,您应该确保socket.ConnectAsync已返回,并且无需将ReceiveMessage()放入update()函数,只需调用它一次即可从python服务器接收数据。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.XR.WSA.WebCam;
using HoloToolkit.Unity.InputModule;
using System;
using System.Linq;
public class Client: MonoBehaviour, IInputClickHandler
{
public string IP;
public int port;
public Text connectButtonText;
public TextMesh debugText;
private PhotoCapture photoCaptureObject = null;
private Texture2D targetTexture = null;
private Resolution cameraResolution;
private TcpNetworkClientManager client = null;
// Use this for initialization
void Start () {
cameraResolution = PhotoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height).First();
//debugText.text = cameraResolution.width.ToString() + " " + cameraResolution.height.ToString();
targetTexture = new Texture2D(cameraResolution.width, cameraResolution.height);
// targetTexture = new Texture2D(480, 270);
// InputManager.Instance.PushFallbackInputHandler(gameObject);
InputManager.Instance.AddGlobalListener(gameObject);
}
void Update()
{
if (client!=null)
{
client.ReceiveMessage();
debugText.text = TcpNetworkClientManager.Name;
}
}
void OnStoppedPhotoMode(PhotoCapture.PhotoCaptureResult result)
{
photoCaptureObject.Dispose();
photoCaptureObject = null;
}
void OnCapturedPhotoToMemory(PhotoCapture.PhotoCaptureResult result, PhotoCaptureFrame photoCaptureFrame)
{
photoCaptureFrame.UploadImageDataToTexture(targetTexture);
//byte[] texByte = targetTexture.EncodeToJPG();
//byte[] image = new byte[texByte.Length];
//Array.Copy(texByte, image, texByte.Length);
byte[] image = targetTexture.GetRawTextureData();
client.SendImage(image);
photoCaptureObject.StopPhotoModeAsync(OnStoppedPhotoMode);
}
public void OnInputClicked(InputClickedEventData eventData)
{
if (client != null)
{
PhotoCapture.CreateAsync(true, delegate (PhotoCapture captureObject)
{
photoCaptureObject = captureObject;
CameraParameters cameraParameters = new CameraParameters();
cameraParameters.hologramOpacity = 0.9f;
cameraParameters.cameraResolutionWidth = cameraResolution.width;
cameraParameters.cameraResolutionHeight = cameraResolution.height;
cameraParameters.pixelFormat = CapturePixelFormat.BGRA32;
photoCaptureObject.StartPhotoModeAsync(cameraParameters, delegate (PhotoCapture.PhotoCaptureResult result)
{
photoCaptureObject.TakePhotoAsync(OnCapturedPhotoToMemory);
});
});
}
}
public void ConnectButtonClicked()
{
if(client != null)
{
Debug.Log("Disconnected");
connectButtonText.text = "Connect";
client = null;
}
else
{
Debug.Log("Connected");
client = new TcpNetworkClientManager(IP, port);
connectButtonText.text = "Disconnect";
}
}
}
def main():
host = "10.24.82.21"
port = 8000
width = 2048
height = 1152
serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serversock.bind((host,port))
serversock.listen(10)
print('Waiting for connections...')
clientsock, client_address = serversock.accept()
print("Succeeded in Connection!")
total = 0
buffer_size = 4*width*height
while True:
data = b''
data = clientsock.recv(buffer_size)
print(len(data))
if len(data) == buffer_size:
tmp = np.frombuffer(data, np.uint8, -1)
img = tmp.reshape(height, width, 4)
#img = cv2.resize(img, (480, 270))
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
img = cv2.flip(img, 0)
#cv2.imshow("img", img)
#cv2.waitKey(1000)
#LoadImages(data)
name = FaceRec(img) #recognize the img and return the name
print (name)
clientsock.sendall(name.encode())
print ("this is " + name)
#cv2.imwrite("out.jpg", img)
#cv2.waitKey(3000)
#cv2.destroyAllWindows()
#break
clientsock.close()
public TcpNetworkClientManager(string IP, int port)
{
#if !UNITY_EDITOR
Connect(IP, port);
#endif
}
#if !UNITY_EDITOR
public async void Connect(string IP, int port)
{
try
{
StreamSocket socket = new StreamSocket();
await socket.ConnectAsync(new HostName(IP), port.ToString());
Stream streamOut = socket.OutputStream.AsStreamForWrite();
writer = new StreamWriter(streamOut) { AutoFlush = true };
Stream streamIn = socket.InputStream.AsStreamForRead();
reader = new StreamReader(streamIn);
ReceiveMessage();
}
catch (Exception e)
{
}
}
#endif