我正在尝试用Unity3D编写一个程序,可以从Python应用程序接收和可视化数据:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Linq;
using System;
public class Visualizer : MonoBehaviour {
TcpListener listener;
private Socket client = null;
private int i = 0;
const int byteCount = 1000;
private const int recvPort = 11000;
static private bool receiverConnected;
static private bool receiverReady;
//TODO: set max message size somehow intelligently
private byte[] bytes = new byte[byteCount];
void Start() {
receiverConnected = false;
receiverReady = false;
IPAddress localAddr = IPAddress.Parse("127.0.0.1"); //always locally
listener = new TcpListener(localAddr, recvPort);
listener.Start();
}
// Update is called once per frame
void Update()
{
if (listener.Pending())
{
client = listener.AcceptSocket();
receiverConnected = true;
}
if (receiverConnected)
{
try
{
int bytesRec;
byte[] allBytes = new byte[byteCount];
bytesRec = client.Receive(allBytes);
if (bytesRec == 0)
{
client.Close();
client.Disconnect(false);
receiverReady = false;
receiverConnected = false;
}
else {
bytes = allBytes.Take(bytesRec).ToArray();
receiverReady = true;
}
catch (Exception e)
{
Debug.Log("Exception in receiving and rendering data");
}
}
//now process:
if (receiverConnected && receiverReady)
{
//DO STUFF
}
}
}
在Python方面,我的程序从以下内容开始:
TCP_IP = '127.0.0.1'
TCP_PORT = 11000
BUFFER_SIZE = 1000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
虽然这在一开始可以正常工作,但在我关闭python应用程序并重新启动它几次之后,s.connect((TCP_IP, TCP_PORT))
开始挂起,程序就再也不会继续了。我想我在处理这些联系的过程中肯定有问题。如何只修改它一点点,以便更优雅地处理关闭和重新打开python端连接请求
将数据传递给花药活动
收到这些数据
如果您想要传递
ArrayList<Form>
,那么使用getParcelableArrayListExtra进行传递通常,请遵循以下步骤:
Form
类正确implement Parcelable在活动发送意图中:
// ArrayList<Form> myList - data to send; intent.putParcelableArrayListExtra("geopoints", myList);
在接收活动中:
ArrayList<Form> myReceivedList = getIntent().getParcelableArrayListExtra("geopoints");
别忘了空/健全检查
希望有帮助
相关问题 更多 >
编程相关推荐