Matlab第二次无法读取套接字

时间:2016-03-16 01:55:53

标签: matlab sockets

我想在两个程序之间进行通信。 MATLAB能够读取套接字一次但是当它再次尝试读取时,我收到以下警告

  

警告:读取失败:在达到终结符之前发生超时。

Matlab代码:

clc
clear all
while(1)
    clear tcpipServer
    tcpipServer = tcpip('127.0.0.1', 55000, 'NetworkRole', 'Server');
    set(tcpipServer, 'Timeout', 30);
    fopen(tcpipServer);
    rawData = fgetl(tcpipServer);
    fclose(tcpipServer);
end

发送到Matlab的数据定义为字符串,值为" y \ n"。 问题是我只收到" y \ n"一旦。 连接到套接字的另一端是Unity游戏引擎。我认为统一中的代码是正确的,因为我通过c #windows app测试了它,只要程序正在运行,我就可以得到它。

有谁知道为什么会这样?

1 个答案:

答案 0 :(得分:0)

这是我找到的解决方案。

Matlab代码:

clc
clear all
%% server  initialization
tcpipServer = tcpip('127.0.0.1',55000,'NetworkRole','Server');
set(tcpipServer,'Timeout',30);
while(1)

%% server code: listening for incoming requests

fopen(tcpipServer);
%rawData = fread(tcpipServer,1,'char');
rawData = fgetl(tcpipServer)
extractedData=str2double(strsplit(rawData,'-'))

fclose(tcpipServer);

Unity C#代码:

using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Linq;
using System;
using System.IO;
using System.Text;


public class server : MonoBehaviour {

    // Use this for initialization
    TcpListener listener;
    String msg;
    StreamWriter theWriter1;
    internal Boolean socketReady = false;
    TcpClient mySocket;
    NetworkStream theStream;
    StreamWriter theWriter;
    StreamReader theReader;
    String Host = "localhost";
    Int32 Port = 55000;
    bool firstTimeRun=true;

    void Start () {

    }
    // Update is called once per frame
    void Update () {
        setupSocket ();
        if (Input.GetMouseButtonDown (0))
            {
            setupSocket ();

            }
    }
    public void setupSocket() {
        try {
            TcpClient mySocket1;
            NetworkStream theStream1;
            //StreamWriter theWriter1;
            mySocket1 = new TcpClient(Host, Port);
            theStream1 = mySocket1.GetStream();
            theWriter1 = new StreamWriter(theStream1);
            Invoke("write", 0.2f);
        }
        catch (Exception e) {
            Debug.Log("Socket error: " + e);
        }
    }
    void write()
    {
        float x;float y;
        x = GameObject.FindGameObjectWithTag ("Player").transform.position.x;
        y=GameObject.FindGameObjectWithTag ("Player").transform.position.y;
        theWriter1.Write(x+"-"+y+"\n");
        theWriter1.Flush();

    }

我使用“\ n”的原因是在Matlab代码中使用 fgetl 函数。如果你想让代码更具功能性,可以使用Unity中的异步任务延迟。对于那些为什么需要使用延迟而徘徊的人,请参阅相关评论。