UDP connection test on BlackBerry Simulator - networking

I am trying to send data using UDP (datagram). I am not able to test application on simulator. I tried running MDS first and then simulator,but it did not work. The error is displayed as Port 8080 already in use on BlackBerry simulator console. How do I change port in simulator? The UDP port to which I am connecting is localhost:5014
I am using simulator for BlackBerry Pearl 8100.

On the Blackberry forum there are comments about issues with datagram under 4.5.0.x up to 4.5.0.83. No wonder there are no UDP samples in sdk.
You always can download 8100 with 4.5.0.108 simulator from http://na.blackberry.com/eng/developers/
Another thing is to use ip, although hostname is allowed in api reference, but when you use MDS simulator it grabs localhost alias.
In the following code you have simple server which is listening to port 135, and bb client which is sending data packet to 127.0.0.1 on port 135.
Desktop server code:
public static void main(String[] args) {
byte[] inBuff = new byte[32];
DatagramSocket socket;
try {
socket = new DatagramSocket(137);
DatagramPacket pckt = new DatagramPacket(inBuff, inBuff.length);
while (true) {
socket.receive(pckt);
System.out.println(new Date() + " " + pckt.getAddress()
+ ":" + pckt.getPort());
socket.send(pckt);
}
} catch (Exception e) {
System.out.println(e.getMessage()+":");
System.out.println(e.getClass().getName());
}
}
BlackBerry client code (tested with Bold 8900 under 4.6.1):
UDPDatagramConnection connection = null;
byte[] outBuff = "Hello!".getBytes();
Datagram outDatagram = null;
try {
connection = (UDPDatagramConnection) Connector
.open("datagram://127.0.0.1:137");
outDatagram = connection.newDatagram(outBuff, outBuff.length);
connection.send(outDatagram);
System.out.println("Datagram packet was sent");
} catch (Exception e) {
System.out.println(e.getMessage()+":");
System.out.println(e.getClass().getName());
}

Related

Why I can't download file from FTP using WebClient in xamarin?

I am makind a simple app in VisualStudio2019 with Xamarin.Forms that will download data from ftp server and show it in my app.
All works fine until I try to use mobile data on DUAL SIM phone. On 1 sim it works fine, on Wi-Fi it works fine, but on sim nr 2 it doesn't want to download the file.
On sim 1 the IP is like 100.50.65.43
On sim 2 the IP is like 192.0.0.7 and 2a00:d58:87dd89ee:5g6h:d9h4:qw54:5560
On Wi-Fi the IP is like 192.168.1.75 and ht98::56n1:78gg:tr5h:j657
I have the INTERNET PERMISSION and NETWORK PERMISSION in android manifest.
Here is the code that I use to download the file:
{
string localFile = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData), "SqLiteData.db3");
string ftpUsername = "Login";
string ftpPassword = "Pass";
var client = new WebClient();
try
{
client.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
client.DownloadFile("ftp://xxx/SqLiteData.db3", localFile);
}
catch (Exception)
{
DisplayAlert(null, "not working", "ok");
}
}

Firewall : Is inbound required for getting response while Outbound rule already there?

I developed one MVC web application which have Web APIs and hosted in Amazon Instance and one windows application for calling those APIs for getting response from that server.
Both Web and Windows applications are developed in asp.net framework 4.5 using c# language.
Windows application is installed in more than 200 client's system which are highly secure servers it selves with all Inbound ports blocked in Firewall.
I am using HttpWebRequest with BindIPEndPoint for calling Web APIs using configured TCP port range [default 7777-7786].
API calls working fine from Windows Application if there are Allow Inbound and Outbound firewall Rules.
But the problem is clients are not allowing me any Inbound Firewall rules, they only allowing Outbound Firewall rules for those port range And Windows application is not working with blocked inbound rules for those port range.
Is it must I need to open Inbound Rule in Firewall for those port range for calling/getting request/response to/from APIs ? If no need of Inbound Firewall rule then please explain Why ?
Below is the API call which use one static TCP port in my Windows Application :
try
{
string address = RevWatchURL;
address = address + "api/GetRevGuardLatestPatch";
HttpWebRequest httpWebRequest = WebRequest.Create(address) as HttpWebRequest;
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
httpWebRequest.Timeout = 300000;
httpWebRequest.ServicePoint.BindIPEndPointDelegate =
new BindIPEndPoint(CommonValues.BindIPEndPointCallbackRGPatch);
string enRevGuardUniqueId =
Encryption.EncryptionTechnique(Convert.ToString(UniqueId), null, null);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"UniqueId\":\"" + enRevGuardUniqueId + "\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
try
{
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
returnVal = streamReader.ReadToEnd();
streamReader.Close();
httpResponse.Close();
}
}
catch (WebException ex)
{
}
finally
{
httpWebRequest.Abort();
}
Obj = JsonConvert.DeserializeObject<CommonValues.RevGuardPatchClass>(returnVal);
}
catch (Exception ex)
{
MessageBox.Show("Error", "API", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
BindIPEndPoint Method:
public static IPEndPoint BindIPEndPointCallbackRGPatch(ServicePoint servicePoint,
IPEndPoint remoteEndPoint, int retryCount)
{
return new IPEndPoint(IPAddress.Any, 7777);
}

Communication with GPRS module using C#, with TCP

I have searched a lot for this but could not find any specific answer that applies to my case. I have made device using GPS module and GSM/GPRS module with Arduino Mega 2560, and it sends me the location through SMS. Now I want to get the location parameters using GPRS. I have in mind to use TCP. I will send data through AT Commands from GPRS module, but I am confused on how to make a server on C#. I know that I would be needing a static/public IP for this. But I don't know how to get the public IP, and start receiving data which I send from GPRS module. Please please I need help because I am a beginner in Client/Server programming, and I am working on my final year project. Many thanks in advance!
please take a look at this TCP server and client example.
You will need a public static IP address. That is something you have to ask your broadband provider, and they will explain you the available options they have, probably you will have to pay extra money. You can use your current public IP address, that will be probably dynamic, but they don't use to change way to often, so whenever you are unable to connect, you will have to check if the IP changed or not, and set the new one.
This video series maybe a good introduction: https://vimeo.com/38103518
Here is the Server Code:
class Server
{
TcpListener server = null;
public Server(string ip, int port)
{
IPAddress localAddr = IPAddress.Parse(ip);
server = new TcpListener(localAddr, port);
server.Start();
StartListener();
}
public void StartListener()
{
try
{
while (true)
{
Console.WriteLine("Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
Thread t = new Thread(new ParameterizedThreadStart(HandleDeivce));
t.Start(client);
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
}
public void HandleDeivce(Object obj)
{
TcpClient client = (TcpClient)obj;
NetworkStream stream = client.GetStream();
string data = null;
Byte[] bytes = new Byte[256];
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("{1}: Received: {0}", data, Thread.CurrentThread.ManagedThreadId);
if (data.StartsWith("##"))
{
data = "LOAD";
}
else
{
data = "ON";
}
byte[] msg = Encoding.ASCII.GetBytes(data);
stream.Write(msg, 0, msg.Length);
Console.WriteLine("{1}: Sent: {0}", data, Thread.CurrentThread.ManagedThreadId);
}
client.Close();
}
}

How to call HTTP URL using wifi in J2ME code for BlackBerry 5.0 and above?

I am calling a web service from BlackBerry using J2ME code. When I try to open a connection using HttpConnection, it is checking only the GPRS connection. Now, I want to check the Wi-Fi connection and call a webservice through Wi-Fi.
The following code is my connection section. How to change the code for a Wi-Fi connection?
public boolean HttpUrl()
{
HttpConnection conn = null;
OutputStream out = null;
String url = "http://www.google.com";
try
{
conn = (HttpConnection) new ConnectionFactory().getConnection(url).getConnection();
if (conn != null)
{
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Length", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
}
}
catch (Exception e)
{
return false;
}
finally
{
try
{
out.close();
}
catch (Exception e2)
{
}
}
//Only if exception occurs, we close the connection.
//Otherwise the caller should close the connection himself.
try
{
conn.close();
}
catch (Exception e1)
{
}
return true;
}
Check this way:
HttpConnection conn = null;
String URL = "http://www.myServer.com/myContent;deviceside=true;interface=wifi";
conn = (HttpConnection)Connector.open(URL);
source
Making Connections
Rafael's answer will certainly work if you know you'll only be using Wi-Fi.
However, if you only need to support BlackBerry OS 5.0 - 7.1, I would recommend that you do use the ConnectionFactory. Normally, you will not limit your code to only using one transport. You'll normally support (almost) any transport the device has, but you may want to code your app to choose certain transports first.
For example,
class ConnectionThread extends Thread
{
public void run()
{
ConnectionFactory connFact = new ConnectionFactory();
connFact.setPreferredTransportTypes(new int[] {
TransportInfo.TRANSPORT_TCP_WIFI,
TransportInfo.TRANSPORT_BIS_B,
TransportInfo.TRANSPORT_MDS,
TransportInfo.TRANSPORT_TCP_CELLULAR
});
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection("http://www.google.com");
if (connDesc != null)
{
HttpConnection httpConn;
httpConn = (HttpConnection)connDesc.getConnection();
try
{
// TODO: set httpConn request method and properties here!
final int iResponseCode = httpConn.getResponseCode();
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("Response code: " +
Integer.toString(iResponseCode));
}
});
}
catch (IOException e)
{
System.err.println("Caught IOException: "
+ e.getMessage());
}
}
}
}
will choose the Wi-Fi transport if Wi-Fi is available, but use the GPRS connection if it isn't. I think this is generally considered best practice for the 5.0+ devices.
Request Properties
This code
conn.setRequestProperty("Content-Length", "application/x-www-form-urlencoded");
is not right. Content-Length should be the size, in bytes, of your HTTP POST parameters. See an example here.
Threading
Remember that making network connections is slow. Do not block the user interface by running this code on the main/UI thread. Put your code into a background thread to keep the UI responsive while you request remote content.

xampp/wamp based Apache server custom reply

How can I send a custom response upon a custom request on a xampp/wamp based Apache server upon a connection to a specific port?
I'm trying to reply to the \0 a flash app is requesting in order to allow a crossdomain http GET request.
The flash policy request, is made to port 843 by default and i'd like to keep it that way.
The port should get a \0 (ending with a null char,\0 is just for the reference) and replying with something like:
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<site-control permitted-cross-domain-policies="master-only"/>
<allow-http-request-headers-from domain="*" headers="*" secure="true" />
<allow-access-from domain="*" to-ports="*" />
</cross-domain-policy>
As far as i know, the request should be return as a plain text, although Content-type, might be needed as well.
I've tried using the following: http://socketpolicyserver.com/ and although it listens to the port and accepts connections, it doesn't reply with the specified xml upon request.
Any methods / ways of achieving a proper reply will be appreciated,
with regards,
Mike.
!---UPDATE--->
I wrote a simple C# web server which listens to port 843, and serves the aforementioned policy - it worked out just fine, however, when using a SecureSocket connection for a secure connection (i.e opening a socket to a HTTPS/SSL protocol) - the request that is sent is encrypted using the hosts certificate. As far as i know, there's no way of listening or acquiring the servers certificate and decrypting the data via an external app hence, the only way is to somehow 'teach' Apache to respond with the crossdomain policy after a proper request is sent via an appropriate port.
Another idea i have is to read the server's certificate file stored in the Apache directory regardless of what happens on the server itself, though imo it's an overkill.
Would love to hear your comments,
Mike.
So here's how i eventually solved it:
I've used this guys code with some modifications: http://www.switchonthecode.com/tutorials/csharp-tutorial-simple-threaded-tcp-server
and created a simple multithreaded web server that listens to port 843, and provides a somewhat general policy upon the appropriate flash request.
There were several examples provided by Adobe, but for some reason, windows didn't like those.
Also note that if you're using the SecureSocket object of flash it should allegedly use the target servers (IIS'/Apaches'/Tomcats' etc..) SSL credentials and will initiate a client Authentication using the public key of the target servers certificate, then again, it might not so this code doesn't have SSL support, although i've started implementing one using C#'s SSL Streams, so far without any luck. If you can make it work via SSL, please let me know.
Hope this code will help,
Mike.
using System;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.IO;
namespace TCPSexyServer
{
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
private void ListenForClients(int p)
{
throw new NotImplementedException();
}
public Server()
{
this.tcpListener = new TcpListener(IPAddress.Any, 843);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//message has successfully been received
UTF8Encoding encoder = new UTF8Encoding();
string sentData = encoder.GetString(message, 0, bytesRead);
Console.WriteLine(sentData);
if (sentData == "<policy-file-request/>\0")
{
String policy = "<?xml version=\"1.0\"?>\n" +
"<!DOCTYPE cross-domain-policy SYSTEM \"/xml/dtds/cross-domain-policy.dtd\">\n" +
"<cross-domain-policy>\n" +
"<site-control permitted-cross-domain-policies=\"master-only\"/>\n" +
"<allow-http-request-headers-from domain=\"*\" headers=\"*\" secure=\"true\" />\n" +
"<allow-access-from domain=\"*\" to-ports=\"*\" />\n" +
"</cross-domain-policy>\0";
byte[] buffer = encoder.GetBytes(policy);
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
Console.WriteLine(policy);
}
else
{
tcpClient.Close();
}
System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
}
tcpClient.Close();
}
public static void Main(string[] args)
{
Server blah = new Server();
}
}
}

Resources