我不太了解 MATLAB 以及如何为它编程,但我会给你一个 AS3 方面的例子。如果你想首先使用 TCP/IP 通信,你需要定义一个服务器和一个客户端。ServerSocket 类仅支持 Flash 端的 AIR 应用程序,因此您应该决定是制作 Flash 端的服务器还是客户端。如果您希望它成为服务器,则需要编写如下内容:
const IP_ADDRESS:String = "127.0.0.1"; //for local hosting
const PORT:uint = 3444; //basically, you can take any port you want, but higher would be better so that it won't have issues with other programs using ports.
var OurServerSocket:ServerSocket = new ServerSocket();
var ConnectedSocket:Socket;
OurServerSocket.addEventListener(ServerSocketConnectEvent.CONNECT, HandleSocketConnection); //adding listener for socket connections, that we'll handle in our method.
OurServerSocket.bind(PORT, IP_ADRESS); //just binding our socket to the IP and port that we defined
OurServerSocket.listen();
function HandleSocketConnection(e:ServerSocketConnectEvent):void
{
ConnectedSocket = e.socket; //just saving connected socket instance
ConnectedSocket.addEventListener(ProgressEvent.SOCKET_DATA, HandleSocketData); //adding listener to handle any data that comes through our connected socket
trace("Connected: " + ConnectedSocket.remoteAddress);
}
function HandleSocketData(e:ProgressEvent):void
{
var socket:Socket = e.target as Socket;
var bytes:ByteArray = new ByteArray();
socket.readBytes(bytes,0,0);
var Data:String = bytes.toString(); //when the data comes in we store it in this string so that you can than manipulate easily
}
//use this function to send data through the connected socket
function WriteToSocket(data:String):void
{
var dataArray:ByteArray = new ByteArray();
dataArray.writeMultiByte(data, "utf-8");
ConnectedSocket.writeBytes(dataArray);
}
如果您决定 Flash 端的客户端连接到您的服务器,如下所示:
var SocketConnection:Socket = new Socket();
SocketConnection.connect(IP_ADDRESS, PORT);
然后,您可以使用相同的写作和阅读方法进行交流。