I have C# application running on dot net compact framework 3.5 on a Windows mobile 6.5 device which utilises TcpClient and NetworkStream to send a byte array to a service running on the host PC. It must be able to communicate by docking the device in a cradle and connecting via Windows Mobile Device Centre, which is set to allow data connections on the device when connected to PC.
I am getting the following error 'Unable to read data from the transport connection'. It works perfectly well when the same device is connected to the network via wifi, but this is not an option as there is no wifi where it will be deployed. It is the nwStream.Write line in the code snippet below where the error occurs:
public bool PostInitialData(string ipAddress, int portNo, string dataString)
{
bool retVal = true;
try
{
IPAddress stringIPAddress = IPAddress.Parse(ipAddress);
TcpClient tcpClient = new TcpClient();
tcpClient.Connect(stringIPAddress, portNo);
NetworkStream nwStream = tcpClient.GetStream();
byte[] bytesToSend = Encoding.ASCII.GetBytes(dataString);
//---send the text
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
//---read back the text
byte[] bytesToRead = new byte[tcpClient.ReceiveBufferSize];
int numBytesRead = nwStream.Read(bytesToRead, 0, tcpClient.ReceiveBufferSize);
string serverResponse = Encoding.ASCII.GetString(bytesToRead, 0, numBytesRead);
tcpClient.Close();
if (serverResponse != "OK")
{
retVal = false;
}
}
catch (Exception ex)
{
LogError.ErrorHandler.LogErrorDetail(ex);
retVal = false;
}
return retVal;
}
Related
We have created codename one application which using https request.
I have not made any changes in code.
Earlier the request could be sent using https but now their is a problem and i am unable to connect to the server using https request but i am able to connect same https url using postman.
The connection code snippet is following please refer it
new APIHandler().PropertiesLoad();
ConnectionRequest req = new ConnectionRequest() {
protected void handleErrorResponseCode(int code, String message) {
if (code != 200) {
// do something
}
}
};
req.setUrl(properties.getProperty("https_url"));
req.setPost(true);
req.setTimeout(Constant.TIMEOUT);
req.addArgument("FirstName", fName;
req.addArgument("SecondName", sName);
req.addArgument("BirthDate", bDate);
req.addArgument("Password", pWord);
NetworkManager.getInstance().addErrorListener((e) -> e.consume());
NetworkManager.getInstance().addToQueueAndWait(req);
byte[] data = req.getResponseData();
if (data == null) {
}
result = new String(data);
} catch (Exception e) {
//get nullpointer exception because result get null
result = "";
}
return result;
I want to send a command to my Sonos speaker. With my Windows application that is easy. I just use the TcpClient example provided on Microsoft website (shown below).
public void Connect(String server, String message)
{
try
{
TcpClient client = new TcpClient(server, 1400);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
//Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
//Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
//Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
// Console.WriteLine("SocketException: {0}", e);
}
//Console.WriteLine("\n Press Enter to continue...");
//Console.Read();
}
Now, how would I go about doing this with Windows 10 IoT on a Raspberry Pi 3?
With UWP, you may need to reference the "System.Net.Sockets" Nuget package in order to use TcpClient. You probably end up with something like below snippet,
async void FunctionName()
{
try
{
using (var client = new TcpClient())
{
await client.ConnectAsync(server, 1400);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
//Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
//Console.WriteLine("Received: {0}", responseData);
}
}
catch (ArgumentNullException e)
{
//Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
// Console.WriteLine("SocketException: {0}", e);
}
//Console.WriteLine("\n Press Enter to continue...");
//Console.Read();
}
Note that you need to declare the Internet client capability in your project manifest file.
PS: There's also an alternative an alternative called StreamSocket.
Refer to an complete code sample from Microsoft github repository.
Also, if you're new to UWP programming, you should get yourself familar with the async/await pattern.
I want to dev a daemon which will capture screen of my OSX at pre login session
I have try by using Quazt display service (stream) and core graphic framework but it still unavailable
my code using Quartz service
m_isExit = FALSE;
m_display = kCGDirectMainDisplay; // 1
m_displayMode = CGDisplayCopyDisplayMode(m_display);
if (m_display == NULL)
{
throw Exception("OSX-Quart service Can not get Display mode ",VF_ERR_SCREEN_MONITOR_OSX_QUART_CREATE);
}
m_height = CGDisplayModeGetHeight(m_displayMode);
m_width = CGDisplayModeGetWidth(m_displayMode);
m_stream = CGDisplayStreamCreate(m_display,m_width,m_height,'BGRA',NULL,VncStreamFrameAvailableHandler);
if (m_stream == NULL)
{
throw Exception("OSX-Quart service Can not create Stream",VF_ERR_SCREEN_MONITOR_OSX_QUART_CREATE);
}
m_screenMonitorThread.start(*this);
it's always through exception.
Another code using Core Graphic framework
m_mainDisplay = kCGDirectMainDisplay;
m_oriImage = CGDisplayCreateImage(m_mainDisplay);
if (m_oriImage == NULL)
{
throw Exception ("Core Graphic Can not Create original Image from display",VF_ERR_SCREEN_MONITOR_OSX_CG_CREATE);
}
ScreenGetConfigure(m_oriImage);
screenData.m_oriImage = m_oriImage;
m_oriPixelDataRef = CGDataProviderCopyData(CGImageGetDataProvider(m_oriImage));
if (m_oriPixelDataRef == NULL)
{
throw Exception ("Core Graphic Can not get pixel data ref",VF_ERR_SCREEN_MONITOR_OSX_CG_CREATE);
}
Both code is not working at pre-login session.
Hope somebody can help me to fix the issue
MacBook, OS X El Capitan (10.11)
I have an application that downloads a video file that is roughly 6mb
I am trying to run this application on a Blackberry Curve 9360, which has 32mb of "media" storage
Sometimes this application runs and is able to download the video with no problems, however other times part way thru downloading the download process fails with an IO exception that states: "There is not enough free memory on the file system to complete this action"
after it fails in this manner I can open up the BlackBerry Desktop software and check the files section and see that the device is indeed reporting that 32/32 mb are full.
If I then restart the device with alt-shift-del and open up blackberry desktop software again the used space has shrunk back down to only 5-6 / 32mb full
Sometimes at this point I am able to run my application now and have it succeed the download, but other times it again gives me the same storage full error. The only thing I can notice that seems like it might be affecting whether or not it fails is how long the download takes total (i.e. it succeeds on wifi, and on good 3g signal and fails on poorer 3g signal, but this is anecdotal at best)
I have used this exact same application on a few different blackberry devices, including a few other Curve devices with the same storage size, and never run into this problem before.
My question is: Has anyone seen a BlackBerry curve device behave in such a way that it will report an incorrect storage space that gets fixed by a reboot?
And is there anything about this download code that could be causing this behavior?
class DownloadThread extends Thread {
public void run()
{
HttpConnection httpConn = null;
InputStream is = null;
try{
httpConn = (HttpConnection)Connector.open(videoUrl + ";interface=wifi");
is = httpConn.openInputStream();
}catch(IOException e){
try{
httpConn = (HttpConnection)Connector.open(videoUrl);
is = httpConn.openInputStream();
}catch(IOException ioe){
System.out.println("891: "+e.toString());
}
}
try{
if (!videoFconn.exists())
videoFconn.create();
else{
videoFconn.delete();
videoFconn.create();
}
OutputStream os = videoFconn.openOutputStream();
lengthOfWebFile = httpConn.getLength();
total = 0;
System.out.println("##################### length of web file = " + lengthOfWebFile + " #################");
byte data[] = new byte[256];
while ((count = is.read(data)) != -1) {
total += count;
progress = (int)(total*100/lengthOfWebFile);
if(model.getValue() < progress){
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
EmbeddedMediaScreen.this.model.setValue(progress);
}
});
}
//write this chunk
os.write(data, 0, count);
Thread.yield();
}
os.flush();
os.close();
is.close();
httpConn.close();
lengthOfLocalFile = videoFconn.fileSize();
System.out.println("###################### Local Length = " + lengthOfLocalFile + "#####################");
if(lengthOfLocalFile == lengthOfWebFile){
amDownloading = false;
startVideo();
}else{
downloadVideo();
}
}catch(FileNotFoundException fnf){
}catch(IOException e){
//ScreenSaverActivity.errorDialog("975: "+e.toString());
System.out.println("980: "+e.toString());
//e.printStackTrace();
}catch(NullPointerException npe){
System.out.println("983: "+npe.toString());
} /*catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}*/
}
public synchronized void postProgress(final int p){
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
//Set the progress bar
EmbeddedMediaScreen.this.model.setValue(p);
}
});
}
}
I basically try to reproduce the Socket example from here: http://www.silverlightshow.net/items/Sockets-and-their-implementation-in-SL2-Beta-1-including-a-chat-like-example.aspx
I only made a small change in the client side, i.e.,
String safeHost = "127.0.0.1";
int port = 4509;
Then I got this permission error? Any idea why?
Unhandled Error in Silverlight Application An attempt was made to access a socket in a way forbidden by its access permissions.
I believe that the way the socket security checks work you need to use the same url string that your application uses. to make sure i am using the correct string i have always used this to construct my DNSEndPoint:
int Port = 4509;
DnsEndPoint ep = new DnsEndPoint(Application.Current.Host.Source.DnsSafeHost, Port, AddressFamily.InterNetwork);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.NoDelay = true;
SocketAsyncEventArgs ea = new SocketAsyncEventArgs{RemoteEndPoint = ep};
//set up completed event handler et al.
sock.ConnectAsync(ea);
I have used this exact code in a similar chat application. By using the Application.Current.Host.Source.DnsSafeHost Property you ensure that you are using the same Dns Name to access the server with the socket that the browser is using for HttpRequests.
Also are you serving the access policy file on port 943, this is another requirement of the socket support in Silverlight.
EDIT
To Confirm that you are serving the policy file you can do a number of things.
install Fiddler, you can use it to debug all http traffic hitting your server, you should be able to see the request for the policy file.
serve your policy file dynamically and then set a break point in your server application to confirm that it is being served. this is what i did.
here is the code i used to serve the policy file:
public abstract class Server
{
protected Socket Listener { get; set; }
protected int Port { get; private set; }
protected int Backlog { get; private set; }
protected bool isStopped { get; set; }
protected SocketAsyncEventArgs AcceptArgs {get;set;}
public Server(int port)
{
AcceptArgs = new SocketAsyncEventArgs();
AcceptArgs.Completed += new EventHandler<SocketAsyncEventArgs>(Accept_Completed);
isStopped = true;
Port = port;
Backlog = 100;
}
public Server(int port, int backlog)
{
isStopped = true;
Port = port;
Backlog = backlog;
}
public void Start()
{
isStopped = false;
Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(IPAddress.Any, Port);
Listener.ExclusiveAddressUse = true;
Listener.Bind(ep);
//Console.WriteLine("Listening on " + Port);
Listener.Listen(Backlog);
Listener.AcceptAsync(AcceptArgs);
}
void Accept_Completed(object sender, SocketAsyncEventArgs e)
{
if (isStopped) return;
Socket client = e.AcceptSocket;
//Console.WriteLine("Accepted Connection From: " + client.RemoteEndPoint.ToString());
e.AcceptSocket = null;
Listener.AcceptAsync(AcceptArgs);
HandleClient(client);
}
public virtual void Stop()
{
if (isStopped) throw new InvalidOperationException("Server already Stopped!");
isStopped = true;
try
{
Listener.Shutdown(SocketShutdown.Both);
Listener.Close();
}
catch (Exception)
{
}
}
protected abstract void HandleClient(Socket Client);
}
public class PolicyServer : Server
{
public const String policyStr = #"<?xml version=""1.0"" encoding=""utf-8"" ?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from>
<domain uri=""*"" />
</allow-from>
<grant-to>
<socket-resource port=""4530"" protocol=""tcp"" />
</grant-to>
</policy>
</cross-domain-access>
</access-policy>";
private byte[] policy = Encoding.ASCII.GetBytes(policyStr);
private static string policyRequestString = "<policy-file-request/>";
public PolicyServer(): base(943)
{
}
protected override void HandleClient(Socket socket)
{
TcpClient client = new TcpClient { Client = socket };
Stream s = client.GetStream();
byte[] buffer = new byte[policyRequestString.Length];
client.ReceiveTimeout = 5000;
s.Read(buffer, 0, buffer.Length);//read in the request string, but don't do anything with it
//you could confirm that it is equal to the policyRequestString
s.Write(policy, 0, policy.Length);
s.Flush();
socket.Shutdown(SocketShutdown.Both);
socket.Close(1);
client.Close();
}
}
Then to use it:
PolicyServer ps = new PolicyServer();
ps.Start();
//then when shutting down
ps.Stop();
I hosted this "server" in the same process that was running the rest of the Chat Server component. Set a breakpoint in HandleClient to confirm if it is receiving the request.