【发布时间】:2016-10-05 21:17:13
【问题描述】:
我想统一做一些模拟。对于我的项目,我想使用 Matlab 作为处理层。所以我想使用套接字进行通信。
这里 Matlab 是服务器,代码如下:
clc
clear all
tcpipServer = tcpip('0.0.0.0',55000,'NetworkRole','Server');
while(1)
b=1
data = membrane(1);
b=2
s = whos('data');
b=3
set(tcpipServer,'OutputBufferSize',s.bytes);
b=4
fopen(tcpipServer);
b=5
fwrite(tcpipServer,'hi');
fclose(tcpipServer);
d=6
end
我使用 1,2,.. 来显示过程
我统一使用此代码
using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System;
using System.IO;
public class Socket : MonoBehaviour {
// Use this for initialization
internal Boolean socketReady = false;
TcpClient mySocket;
NetworkStream theStream;
StreamWriter theWriter;
StreamReader theReader;
String Host = "localhost";
Int32 Port = 55000;
void Start () {
setupSocket ();
Debug.Log ("socket is set up");
Debug.Log (readSocket()+" is the message");
closeSocket ();
Debug.Log ("Socket is closed");
}
// Update is called once per frame
void Update () {
}
public void setupSocket() {
try {
mySocket = new TcpClient(Host, Port);
theStream = mySocket.GetStream();
theWriter = new StreamWriter(theStream);
theReader = new StreamReader(theStream);
socketReady = true;
}
catch (Exception e) {
Debug.Log("Socket error: " + e);
}
}
public String readSocket() {
if (!socketReady)
return "";
if (theStream.DataAvailable)
return theReader.ReadLine();
return "";
}
public void closeSocket() {
if (!socketReady)
return;
theWriter.Close();
theReader.Close();
mySocket.Close();
socketReady = false;
}
}
首先我启动 Matlab,然后我玩统一。结果是,连接正常,但我无法读取 Matlab 发送的数据
这是我在 Matlab 中得到的
b =
1
b =
2
b =
3
b =
4
b =
5
d =
6
b =
1
b =
2
b =
3
b =
4
最后这就是我团结起来的结果
socket is set up
is the message
Socket is closed
预期结果是
socket is set up
hi is the message
Socket is closed
我不知道如何读取数据以及如何实现它。
谢谢
【问题讨论】:
-
你不是把服务器/客户端搞混了吗?基于the documentation 如果您希望
tcpip对象将数据写入套接字,它需要是客户端而不是服务器。 -
你是对的。但它可以通过两个 Matlab 会话正确工作。现在我将数据从统一发送到 Matlab,我可以读取它。下一个挑战是反之亦然。谢谢@Suever