When I execute the following:
private function setUpRecvStream():void {
writeText("Connecting to: " + theirID);
recvStream = new NetStream(netConnection, theirID);
recvStream.addEventListener(NetStatusEvent.NET_STATUS, netStreamHandler);
//play the recvStream
recvStream.play("media");
//attach the stream videoRecv
videoRecv.attachNetStream(recvStream);
}
Using a vaild string for theirID I'm getting the following:
Connecting to: 8640d30e760528b2c88662eacef67d693527e52549eb5e29fc405355a7db147e
NetStream.Connect.Closed
I'm expecting NetStream.Connect.Success since I'm passing in a vaild string for theirID. Any ideas why this might be happening?
Are you initializing your netConnection? Also, the stream you are connecting to might not be publishing "media".
The client you are connecting to must do sendStream.publish("media")
before using this you need to connect to FMS
nc = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusEvent);
nc.connect('rtmfp://stratus.adobe.com/cbd2224f9a56771b3d4d05c3-bd9b549abca2');
private function netStatusEvent(event:NetStatusEvent):void {
trace('NetConnection status event (1): ' + event.info.code);
if (event.info.code == 'NetConnection.Connect.Success'){
}
}
Related
I am trying to retrieve a value from a Zebra printer by interrogating it with this code:
public static string GetSettingFromPrinter(string cmd)
{
string setting = string.Empty;
try
{
BasicPortSettings bps = new BasicPortSettings();
bps.BaudRate = BaudRates.CBR_19200;
bps.Parity = OpenNETCF.IO.Serial.Parity.none;
bps.StopBits = OpenNETCF.IO.Serial.StopBits.one;
Port serialPort = new Port("COM1:", bps);
serialPort.Open();
byte[] sendBytes = Encoding.ASCII.GetBytes(cmd);
MessageBox.Show(Encoding.ASCII.GetString(sendBytes, 0, sendBytes.Length));
serialPort.Output = sendBytes;
serialPort.Query(); // <= this is new
byte[] responseBytes = serialPort.Input;
setting = GetString(responseBytes);
serialPort.Close();
return setting;
}
catch (Exception x)
{
MessageBox.Show(x.ToString());
return setting;
}
}
However, I don't see where the Output is actually sent, or how to do that. My best guess was calling the Port.Query() method, but that doesn't work, either - at least there is nothing in setting / the Port.Input value after doing so.
I have successfully passed commands to the printer using the older SerialPort class:
public static bool SendCommandToPrinter(string cmd)
{
bool success; // init'd to false by default
try
{
SerialPort serialPort = new SerialPort();
serialPort.BaudRate = 19200;
serialPort.Handshake = Handshake.XOnXOff;
serialPort.Open();
serialPort.Write(cmd);
serialPort.Close();
success = true;
}
catch // may not need a try/catch block, as success defaults to false
{
success = false;
}
return success;
}
...but was advised not to use that due to its longness of tooth.
I would revert back to this snaggletooth if I knew how to read from the old SerialPort class. Does anybody know what I need to do to send sendBytes (and receive responseBytes)?
UPDATE
I tested "COM1" instead of "COM1:" (I used the latter because there is a post that says the colon is necessary (<= not medical advice, although that is doubtless true in that sense, too), but sans the ":" made no noticeable difference.
I then tried "string.Empty" in place of giving it a name, and got, "OpenNETCF.IO.Serial.CommPortException: CreateFileFailed 2 ..."
Onward...or is it Sideward...
FWIW, setting the Output property immediately sends the data on the wire. No additional call is necessary.
I've written HttpUrlConnection wrapper. It supports file uploading, so I'm using HttpUrlConnection.setChunkedStreamingMode() to prevent OutOfMemoryException.
But after writing all data to OutputStream I getting IOException. Without this method everything works fine.
Here the code:
HttpURLConnection connection = getConnection();
if(!isSent) {
OutputStream output;
if(!files.isEmpty()) {
connection.setRequestProperty(HEADER_CONTENT_TYPE, CONTENT_TYPE_MULTIPART);
// Tried to add this line, but still not working
connection.setRequestProperty("Transfer-Encoding","chunked");
connection.setChunkedStreamingMode(chunkSize);
output = new BufferedOutputStream(connection.getOutputStream());
writeParamsMultipart(output);
writeFilesMultipart(output);
output.write((PREFIX + BOUNDARY + PREFIX + LINEND).getBytes());
} else {
connection.setRequestProperty(HEADER_CONTENT_TYPE, CONTENT_TYPE_FORM);
output = new BufferedOutputStream(connection.getOutputStream());
output.write(paramsToUrlencoded(post).getBytes());
}
output.flush();
output.close();
isSent = true;
}
// Getting exception on this line
InputStream input = new BufferedInputStream(connection.getInputStream());
if(ENCODING_GZIP.equalsIgnoreCase(connection.getHeaderField(HEADER_CONTENT_ENCODING))) {
input = new GZIPInputStream(input);
}
return input;
chunkSize by default 1024 bytes. What's the problem?
It's FileNotFoundException
That means that the URL is incorrect. It's the equivalent of HTTP 403.
Nothing to do with chunked transfer mode.
I am trying to use Ti.Network.TCPSocket to login to an IMAP server.
Its hard as I am not receiving anything back to debug with. For example:
var socket = Ti.Network.createTCPSocket("imap.gmail.com", 993);
socket.connect();
socket.write("LOGIN user pass\r\n");
//event handlers
socket.onWrite(function(data) {
Ti.API.debug('Written to socket: '+data);
});
socket.onError(function(data) {
Ti.API.debug(data);
});
I am not getting anything back. Not even an error or some sort of code or acknowledgement that something is actually happening.
Am I doing something wrong here?
How can I get these even handlers to work or the socket to return some sort of message.
Any help would be appreciated.
UPDATE - Full Code
Ti.API.debug('Start A socket Connection');
var socket = Ti.Network.createTCPSocket("imap.gmail.com", 993);
Ti.API.debug('Connect the socket');
socket.connect();
Ti.API.debug('Socket Connected');
var command = uniqueid()+" LOGIN USER PASS\r\n";
socket.write(command);
//this is where the debug stops. No echo.
Ti.API.debug('Command Run');
socket.onWrite(function(data) {
Ti.API.debug('Written to socket: '+data);
});
socket.onError(function(data) {
Ti.API.debug('Error: '+data);
});
socket.onReadComplete(function(data) {
Ti.API.debug('Here: '+data);
});
function uniqueid() {
var s = [];
var hexDigits = "0123456789abcdef";
for (var i = 0; i < 10; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4";
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
s[8] = s[13] = s[18] = s[23];
var uuid = s.join("");
return uuid;
}
Port 993 is for IMAP over SSL.
onWrite doesn't exist - thats a bug, and probably why your debug statements stop.
try moving your socket.connect() to after you define the handlers.
Use an interval, and socket.isClosed() before trying to write to the socket. Once you get a socket.isClosed() == false, then go ahead. Once you have the socket, you can play with it in the webinspector console in app as well.
This won't solve all your problems, but may help. You might want to try using a utility like wireshark to see what exactly you are sending down the wire when you socket.write, and compare that with what your email client sends.
I wrote some basic functions in ActionScript in order to use RTMFP:
import flash.events.NetStatusEvent;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.ui.Keyboard;
private var serverAddress:String = "rtmfp://cc.rtmfp.net/";
private var serverKey:String = "xxxxx";
private var netConnection:NetConnection;
private var outgoingStream:NetStream;
private var incomingStream:NetStream;
private function initConnection():void {
netConnection = new NetConnection();
netConnection.addEventListener(NetStatusEvent.NET_STATUS, netConnectionHandler);
netConnection.connect(serverAddress + serverKey);
}
private function netConnectionHandler(event:NetStatusEvent):void {
receivedMessages.text += "NC Status: " + event.info.code + "\n";
//Some status handling will be here, for now, just print the result out.
switch (event.info.code) {
case 'NetConnection.Connect.Success':
receivedMessages.text += "My ID: " + netConnection.nearID + "\n";
break;
}
}
private function sendInit():void {
outgoingStream = new NetStream(netConnection, NetStream.DIRECT_CONNECTIONS);
outgoingStream.addEventListener(NetStatusEvent.NET_STATUS, outgoingStreamHandler);
outgoingStream.publish("media");
var sendStreamObject:Object = new Object();
sendStreamObject.onPeerConnect = function(sendStr:NetStream):Boolean {
receivedMessages.text += "Peer Connected ID: " + sendStr.farID + "\n";
return true;
}
outgoingStream.client = sendStreamObject;
}
private function receiveInit():void {
receivedMessages.text += "Initializing Receiving Stream: " + incomingID.text + "\n";
incomingStream = new NetStream(netConnection, incomingID.text);
incomingStream.addEventListener(NetStatusEvent.NET_STATUS, incomingStreamHandler);
incomingStream.play("media");
incomingStream.client = this;
}
public function receiveMessage(message:String):void {
receivedMessages.text += "Received Message: " + message + "\n";
}
private function outgoingStreamHandler(event:NetStatusEvent):void {
receivedMessages.text += "Outgoing Stream: " + event.info.code + "\n";
}
private function incomingStreamHandler(event:NetStatusEvent):void {
receivedMessages.text += "Incoming Stream: " + event.info.code + "\n";
}
private function sendMessage():void {
outgoingStream.send("receiveMessage", toSendText.text);
}
private function disconnectNetConnection():void {
netConnection.close();
netConnection.removeEventListener(NetStatusEvent.NET_STATUS, netConnectionHandler);
netConnection = null;
}
private function disconnectOutgoing():void {
outgoingStream.close();
outgoingStream.removeEventListener(NetStatusEvent.NET_STATUS, outgoingStreamHandler);
outgoingStream = null;
}
private function disconnectIncoming():void {
incomingStream.close();
incomingStream.removeEventListener(NetStatusEvent.NET_STATUS, incomingStreamHandler);
incomingStream = null;
}
initConnection initializes the NC, sendInit initializes the send
stream, receiveInit initializes the incoming stream based on the far peer
id which I copy paste into incomingID.text
I print every results into receivedMessages.text
I do not have firewall, nor NAT.
The Adobe sample application
(http://labs.adobe.com/technologies/cirrus/samples/) works perfectly.
The procedure I follow:
Initialize NC on application 1. (sender)
Initialize NC on application 2. (receiver)
I copy the far peer id to application 2. and run receveInit.
I initialize the sending stream (sendInit) on application 1.
Note: I tried to reverse the last 2 procedure, doesent work either way.
After this, I execute sendMessage() which reads the message from toSendText.text.
Does not working. Why?
What is wrong with my codes?
Thank you for every helpful answer in advance.
because cc.rtmfp.net is the connectivity checker, not the P2P introduction service (p2p.rtmfp.net). cc performs some quick tests, sends the results, and disconnects. it performs no other functions nor provides any other services.
I found out.
For developing and testing, I use Mac and I tested the application there. Did not work. Still doesen't work.
On Windows, it works perfectly.
Strange.
You have to add Handler for receiveMessage(). Otherwise it is just a function that you have to call it.
How do I use crossdomain with ftp?
I am trying to do a "hello world" level test of FTP in Flex, but for three days now, I cannot overcome the issue with how to coerce flex into accepting my crossdomain policy - even for testing purposes.
Here is my code: The exact error text follows.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" initialize="onInitialize()" layout="vertical">
<mx:Script>
<![CDATA[
import mx.utils.*;
import mx.controls.Alert;
private var fileRef:FileReference;
private var fileSize:uint;
private var fileContents:ByteArray;
//you need to initiate two scokets one for sending
//commands and second for sending data to FTP Server
//socket for sending commands to FTP
private var s:Socket
//responce from FTP
private var ftpResponce:String;
//socket for sending Data to FTP
private var dataChannelSocket:Socket;
//responce from FTP when sending Data to FTP
private var dataResponce:String;
//will hold the IP address of new socket created by FTP
private var dataChannelIP:String;
//will hold the Port number created by FTP
private var dataChannelPort:int;
private var user:String="I have the right user"; //FTP usernae
private var pass:String="the pw is correct"; //FTP Password
private function receiveReply(e:ProgressEvent):void {
ftpResponce=s.readUTFBytes(s.bytesAvailable)
var serverResponse:Number=Number(ftpResponce.substr(0, 3));
if (ftpResponce.indexOf('227') > -1) {
//get the ip from the string response
var temp:Object=ftpResponce.substring(ftpResponce.indexOf("(") + 1
, ftpResponce.indexOf(")"));
var dataChannelSocket_temp:Object=temp.split(",");
dataChannelIP=dataChannelSocket_temp.slice(0, 4).join(".");
dataChannelPort=parseInt(dataChannelSocket_temp[4]) * 256 +
int(dataChannelSocket_temp[5]);
//create new Data Socket based on dataChannelSocket and dataChannelSocket port
dataChannelSocket=new Socket(dataChannelIP, dataChannelPort);
dataChannelSocket.addEventListener(ProgressEvent.SOCKET_DATA, receiveData);
}
//few FTP Responce Codes
switch (String(serverResponse)) {
case "220":
//FTP Server ready responce
break;
case "331":
//User name okay, need password
break;
case "230":
//User logged in
break;
case "250":
//CWD command successful
break;
case "227":
//Entering Passive Mode (h1,h2,h3,h4,p1,p2).
break;
default:
}
//for more please
//http://http://www.altools.com/image/support/alftp/ALFTP_35_help/
//FTP_response_codes_rfc_959_messages.htm
traceData(ftpResponce);
}
private function receiveData(e:ProgressEvent):void {
dataResponce=dataChannelSocket.readUTFBytes(
dataChannelSocket.bytesAvailable);
traceData("dataChannelSocket_response—>" + dataResponce);
}
private function showError(e:IOErrorEvent):void {
traceData("Error—>" + e.text);
}
private function showSecError(e:SecurityErrorEvent):void {
traceData("SecurityError–>" + e.text);
}
private function onInitialize():void {
Security.loadPolicyFile("http://www.myUrlIsCorrectInMyProgram.com/crossdomain.xml");
}
private function createRemoteFile(fileName:String):void {
if (fileName != null && fileName != "") {
s.writeUTFBytes("STOR " + fileName + "\n");
s.flush();
}
}
private function sendData():void {
fileContents=fileRef.data as ByteArray;
fileSize=fileRef.size;
dataChannelSocket.writeBytes(fileContents, 0, fileSize);
dataChannelSocket.flush();
}
//initialize when application load
private function upLoad():void {
fileRef=new FileReference();
//some eventlistener
fileRef.addEventListener(Event.SELECT, selectEvent);
fileRef.addEventListener(Event.OPEN, onFileOpen);
//this function connects to the ftp server
connect();
//send the usernae and password
this.userName(user);
this.passWord(pass);
//if you want to change the directory for upload file
this.changeDirectory("/test/"); //directory name
//enter into PASSV Mode
s.writeUTFBytes("PASV\n");
s.flush();
}
private function onFileOpen(event:Event):void {
}
private function traceData(event:Object):void {
var tmp:String="================================\n";
ta.text+=event.toString() + "\n";
ta.verticalScrollPosition+=20;
}
private function ioErrorEvent(event:IOErrorEvent):void {
Alert.show("IOError:" + event.text);
}
private function selectEvent(event:Event):void {
btn_upload.enabled=true;
filename.text=fileRef.name;
fileRef.load();
}
private function uploadFile():void {
createRemoteFile(fileRef.name);
sendData();
}
private function connect():void {
s=new Socket("ftp.myUrlIsCorrectInMyProgram.com", 21);
s.addEventListener(ProgressEvent.SOCKET_DATA, receiveReply);
s.addEventListener(IOErrorEvent.IO_ERROR, showError);
s.addEventListener(SecurityErrorEvent.SECURITY_ERROR, showSecError);
s.addEventListener(Event.CONNECT, onSocketConnect);
s.addEventListener(Event.CLOSE, onSocketClose);
s.addEventListener(Event.ACTIVATE, onSocketAtivate);
}
private function onSocketConnect(evt:Event):void {
//traceData("OnSocketConnect–>"+evt.target.toString());
}
private function onSocketClose(evt:Event):void {
//traceData("onSocketClose–>"+evt.target.toString());
}
private function onSocketAtivate(evt:Event):void {
//traceData("onSocketAtivate–>"+evt.target.toString());
}
private function userName(str:String):void {
sendCommand("USER " + str);
}
private function passWord(str:String):void {
sendCommand("PASS " + str);
}
private function changeDirectory(str:String):void {
sendCommand("CWD " + str);
}
private function sendCommand(arg:String):void {
arg+="\n";
s.writeUTFBytes(arg);
s.flush();
}
]]>
[SWF] /FTP-debug/FTP.swf - 739,099 bytes after decompression
Warning: Domain www.myUrlIsCorrectInMyProgram.com does not specify a meta-policy. Applying default meta-policy 'master-only'. This configuration is deprecated. See http://www.adobe.com/go/strict_policy_files to fix this problem.
Warning: Timeout on xmlsocket://ftp.myUrlIsCorrectInMyProgram.com:843 (at 3 seconds) while waiting for socket policy file. This should not cause any problems, but see http://www.adobe.com/go/strict_policy_files for an explanation.
Warning: [strict] Ignoring policy file at xmlsocket://ftp.myUrlIsCorrectInMyProgram.com:21 due to incorrect syntax. See http://www.adobe.com/go/strict_policy_files to fix this problem.
* Security Sandbox Violation *
Connection to ftp.myUrlIsCorrectInMyProgram.com:21 halted - not permitted from http://localhost/FTP-debug/FTP.swf
Error: Request for resource at xmlsocket://ftp.myUrlIsCorrectInMyProgram.com:21 by requestor from http://localhost/FTP-debug/FTP.swf is denied due to lack of policy file permissions.
The "Information" at the URL's listed above is categorically unintelligable to me.
Please, someone help!
I also had the same issue but was able to fix it using the flash policy server that I downloaded from http://www.flash-resources.net/download.html.
I ran this on the same machine that I have my tomcat server installed and made the call
Security.loadPolicyFile("xmlsocket://:843");
from the application and it worked perfectly. No errors.
I also had the same issue but was able to fix it using the flash policy server that I downloaded from here.
I ran this on the same machine that I have my tomcat server installed and made the call
Security.loadPolicyFile("xmlsocket://Machine Name:843");
from the application and it worked perfectly. No errors.
Watch the typo around the Machine Name in the last post.
See the crossdomain spec:
http://learn.adobe.com/wiki/download/attachments/64389123/CrossDomain_PolicyFile_Specification.pdf?version=1
This covers the warning you have and can help you get this working.