我在Action Script 3中有一个UDP套接字程序,在Flash CS6中编译Adobe Air并且我一直收到错误
TypeError:错误#1009:无法访问空对象引用的属性或方法。 在Untitled_fla :: MainTimeline / fl_MouseClickHandler()[Untitled_fla.MainTimeline :: frame1:64]
这是我的代码:
import flash.display.Sprite;
import flash.events.DatagramSocketDataEvent;
import flash.events.Event;
import flash.net.DatagramSocket;
import flash.utils.ByteArray;
var datagramSocket:DatagramSocket;
//The IP and port for this computer
var localIP:String = iploc.text;
var localPort:int = portloc.value;
//The IP and port for the target computer
var targetIP:String = ipto.text;
var targetPort:int = portto.value;
function DatagramSocketExample()
{
//Create the socket
datagramSocket = new DatagramSocket();
datagramSocket.addEventListener( DatagramSocketDataEvent.DATA, dataReceived );
//Bind the socket to the local network interface and port
datagramSocket.bind( localPort, localIP );
//Listen for incoming datagrams
datagramSocket.receive();
//Create a message in a ByteArray
}
function dataReceived( event:DatagramSocketDataEvent ):void
{
//Read the data from the datagram
trace("Received from " + event.srcAddress + ":" + event.srcPort + "> " +
event.data.readUTFBytes( event.data.bytesAvailable ) );
rcv.text = event.data.readUTFBytes( event.data.bytesAvailable )
}
sendbtn.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
function fl_MouseClickHandler(event:MouseEvent):void
{
var data:ByteArray = new ByteArray();
data.writeUTFBytes(msg.text);
//Send the datagram message
datagramSocket.send( data, 0, 0, targetIP, targetPort);
}
请帮帮我。
答案 0 :(得分:0)
我认为ipto
是一个动态文本字段,设置为"输入文本"但是什么是portto
?
如果它也是动态文本字段,您应该尝试从中获取字符串并将其转换为整数。
var targetIP:String = ipto.text;
var targetPort:int = (int)portto.text;
另外,请务必检查ipto
和portto
是否是实际的实例名称而不只是其符号名称。
我有时倾向于创建文本字段而忘记选择实例名称。
答案 1 :(得分:0)
为什么呢? - 因为你还没有调用DatagramSocketExample()
函数。所以它没有设置addEventListener()
和bind()
这里有一些有效的测试代码。绑定到localhost 127.0.0.1和相同的端口,以便您可以看到它通过dataReceived()
事件函数接收数据。
import flash.display.Sprite;
import flash.events.DatagramSocketDataEvent;
import flash.events.Event;
import flash.net.DatagramSocket;
import flash.utils.ByteArray;
var datagramSocket: DatagramSocket;
var localIP: String = "127.0.0.1";
var localPort: int = 1;
var targetIP: String = "127.0.0.1";
var targetPort: int = 1;
datagramSocket = new DatagramSocket();
datagramSocket.addEventListener(DatagramSocketDataEvent.DATA, dataReceived);
datagramSocket.bind(localPort, localIP);
datagramSocket.receive();
var data: ByteArray = new ByteArray();
data.writeUTFBytes("Test data");
datagramSocket.send(data, 0, 0, targetIP, targetPort);
function dataReceived(event: DatagramSocketDataEvent): void {
trace("Received from " + event.srcAddress + ":" + event.srcPort + "> " + event.data.readUTFBytes(event.data.bytesAvailable));
}