I've got a device to my computer and I want to read its data from port 2005
I use the following code to read from the 2005 port.
public MainWindow()
{
try
{
IPAddress localAddr = IPAddress.Parse("0.0.0.0");
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localAddr = IPAddress.Parse(ip.ToString());
}
}
TcpClient client = null;
try
{
client = new TcpClient(localAddr.ToString(), 2005);
}
catch (SocketException se)
{
}
Byte[] bytes = new Byte[256];
String data = null;
while (true)
{
data = null;
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
DecodeReceivedMsg(data);
}
client.Close();
}
}
catch (SocketException e)
{
}
finally
{
}
}
My problem is that I do not always read the port, and many times, the while(true) does not run.
please guide me
Related
I used libUsbDotNet library (C#) to read data from USB device.
The program sees the device and turns to it, but gives a response IoTimedOut.
The program code is shown below.
public static UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(0x10C4, 0xEA61);
public static UsbDevice MyUsbDevice;
public static void Main()
{
MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
if (MyUsbDevice == null) throw new Exception("Device Not Found.");
IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
wholeUsbDevice.SetConfiguration(1);
wholeUsbDevice.ClaimInterface(0);
}
UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
ErrorCode ec = ErrorCode.None;
int bytesRead = 0;
byte[] readBuffer = new byte[32];
while (true) {
Thread.Sleep(100);
ec = reader.Read(readBuffer, 1500, out bytesRead);
if (bytesRead > 0)
{
Console.WriteLine("Data Received");
// Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead));
}
else {
Console.Write("Error type: ");
Console.WriteLine(ec);
Console.ReadKey();
MyUsbDevice.Close();
break;
}
}
}
I tried to change the reading parameters but it doesn't help. Can you please tell me what it may be related to, it is not clear to me from the libUsbDotNet documentation?
Using Xamarin.Forms app. When mobile data connection fluctuates on Android devices, e.g. network from 3G to 2G connection, or vice versa - the call seems to get hung somewhere.
This is the Azure API call :
public Task<ObservableCollection<Models.Item>> GetItemsByID(string tenantID, string auth_token)
{
return Task.Factory.StartNew(() =>
{
var res = RestClient.Get<ObservableCollection<Models.Item>>(HttpWebRequest.Create(string.Format(EndPointsList.GetItemsUrl + "tenantID={0}", tenantID)),auth_token);
return res ;
});
}
We initiate the System.Net.WebRequest here :
public static T Get<T>(WebRequest request, string auth_token, string requestData = null)
{
string result = string.Empty;
request.ContentType = "application/json";
request.Headers["ZUMO-API-VERSION"] = "2.0.0";
if (auth_token.StartsWith("Bearer"))
request.Headers["Authorization"] = auth_token;
else {
request.Headers["x-access_type"] = "offline";
request.Headers["x-zumo-auth"] = auth_token;
}
try
{
WebResponse webResponse = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null).Result;
using (var streamReader = new StreamReader(webResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
var typ = typeof(T);
if (
typ == typeof(String)
|| typ == typeof(float)
|| typ == typeof(Decimal)
|| typ == typeof(Int16)
|| typ == typeof(Int32)
|| typ == typeof(Int64)
)
{
return (T)Convert.ChangeType(result, typeof(T), null);
}
return result.FromJson<T>();
}
catch (AggregateException agEx)
{
AggregateException(agEx);
return result.FromJson<T>();
}
catch (Exception ex)
{
return result.FromJson<T>();
}
}
This is the call from ViewModel
public async Task GetAllItems()
{
try
{
if (!this.IsInternetConnectionAvailable())
{
await this.CurrentContentPage.DisplayAlert("", AppResources.InternetConnectionNotAvailable, AppResources.Ok);
return;
}
this.ProgressBar.ShowProgress(AppResources.Loading);
ItemList = await this.ItemService.GetItemsByID(App.Locator.Login.LoggedInUser.TenantID.ToString(),Settings.AuthToken);
if (ItemList != null)
{
for (int i = 0; i < this.ItemList.Count; i++)
{
ItemList[i].RowColor = (i % 2 == 0 ? Theme.EvenRowColor : Theme.OddRowColor);
}
}
RaisePropertyChanged("ItemList");
}
catch (Exception ex)
{
ExceptionHandler.HandleException(CurrentContentPage, ex);
}
finally
{
this.ProgressBar.Dismiss();
}
}
In actual case here - the ProgressBar will kept on be displayed on the device, though its in Finally block. User have to kill the application to make it work again.
And we're unsuccessful to reproduce this back in lab. It only happens on field during intermittent connections.
Any abnormalities in the code? If not, how can we capture this in application log.
I am using following code for getting contents of a web page
String url = "http://abc.com/qrticket.asp?qrcode="
+ "2554";
try {
url += ";deviceside=true;interface=wifi;ConnectionTimeout=" + 50000;
HttpConnection connection = (HttpConnection) Connector.open(url,
Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.GET);
// connection.openDataOutputStream();
InputStream is = connection.openDataInputStream();
String res = "";
int chr;
while ((chr = is.read()) != -1) {
res += (char) chr;
}
is.close();
connection.close();
showDialog(parseData(res));
} catch (IOException ex) {
ex.printStackTrace();
showDialog("http: " + ex.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
showDialog("unknown: " + ex.getMessage());
}
public void showDialog(final String text) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(text);
}
});
}
public String parseData(String str) {
String[] data = split(str, "//");
StringBuffer builder = new StringBuffer();
for (int i = 0; i < data.length; i++) {
System.out.println("data:" + data[i]);
String[] vals = split(data[i], ">>");
if (vals.length > 1) {
System.out.println(vals[0]);
builder.append(vals[0].trim()).append(": ")
.append(vals[1].trim()).append("\n");
} else {
builder.delete(0, builder.toString().length()).append(
vals[0].trim());
break;
}
}
return builder.toString();
}
public String[] split(String splitStr, String delimiter) {
// some input validation
if (delimiter == null || delimiter.length() == 0) {
return new String[] { splitStr };
} else if (splitStr == null) {
return new String[0];
}
StringBuffer token = new StringBuffer();
Vector tokens = new Vector();
int delimLength = delimiter.length();
int index = 0;
for (int i = 0; i < splitStr.length();) {
String temp = "";
if (splitStr.length() > index + delimLength) {
temp = splitStr.substring(index, index + delimLength);
} else {
temp = splitStr.substring(index);
}
if (temp.equals(delimiter)) {
index += delimLength;
i += delimLength;
if (token.length() > 0) {
tokens.addElement(token.toString());
}
token.setLength(0);
continue;
} else {
token.append(splitStr.charAt(i));
}
i++;
index++;
}
// don't forget the "tail"...
if (token.length() > 0) {
tokens.addElement(token.toString());
}
// convert the vector into an array
String[] splitArray = new String[tokens.size()];
for (int i = 0; i > splitArray.length; i++) {
splitArray[i] = (String) tokens.elementAt(i);
}
return splitArray;
}
This is working absolutely fine in simulator but giving 'http:null' (IOException) on device, I dont know why??
How to solve this problem?
Thanks in advance
I think the problem might be the extra connection suffixes you're trying to add to your URL.
http://abc.com/qrticket.asp?qrcode=2554;deviceside=true;interface=wifi;ConnectionTimeout=50000
According to this BlackBerry document, the ConnectionTimeout parameter isn't available for Wifi connections.
Also, I think that if you're using Wifi, your suffix should simply be ";interface=wifi".
Take a look at this blog post on making connections on BlackBerry Java, pre OS 5.0. If you only have to support OS 5.0+, I would recommend using the ConnectionFactory class.
So, I would try this with the url:
http://abc.com/qrticket.asp?qrcode=2554;interface=wifi
Note: it's not clear to me whether your extra connection parameters are just ignored, or are actually a problem. But, since you did get an IOException on that line, I would try removing them.
The problem was that no activation of blackberry internet service. After subscription problem is solved.
Thanks alto all of you especially #Nate
Hi am trying to run my app on blackberry device using Edge gprs connection but its not rendering the pages.i have tried lot to get the connection,also i tried the various links to solve, one of the simple code i have attached here, kindly guide me to solve this
public static String getConnectionString() {
String value="" ;
if(WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
value=";interface=wifi";
}else{
value=";deviceside=true";
}
return value;
}
Append the connection string to your url. Then try
public static String getConnectionString() {
// This code is based on the connection code developed by Mike Nelson of
// AccelGolf.
// http://blog.accelgolf.com/2009/05/22/blackberry-cross-carrier-and-cross-network-http-connection
String connectionString = null;
// Simulator behavior is controlled by the USE_MDS_IN_SIMULATOR
// variable.
if (DeviceInfo.isSimulator()) {
connectionString = ";deviceSide=true";
}
// Wifi is the preferred transmission method
else if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
// System.out.println("Device is connected via Wifi.");
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// System.out.println("Carrier coverage.---->>" + CoverageInfo.getCoverageStatus());
String carrierUid = getCarrierBIBSUid();
// DebugScreen.Log(" carrierUid is: " + carrierUid);
if (carrierUid == null) {
// Has carrier coverage, but not BIBS. So use the carrier's TCP
// network
// System.out.println("No Uid");
String wapString = getAvailableConnectionsString();
// DebugScreen.Log("from wap2 connection--->" + wapString);
if(wapString == null){
connectionString = ";deviceside=true";
}else{
connectionString = wapString;
}
} else {
// otherwise, use the Uid to construct a valid carrier BIBS
// request
connectionString = ";deviceside=true;connectionUID=" + carrierUid + ";ConnectionType=mds-public";
}
}
// Check for an MDS connection instead (BlackBerry Enterprise Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
// System.out.println("MDS coverage found");
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid bugging the user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
// System.out.println("There is no available connection.");
}
// In theory, all bases are covered so this shouldn't be reachable.
else {
// System.out.println("no other options found, assuming device.");
connectionString = ";deviceside=true";
}
return connectionString;
}
Add this method and append connection String to url.
private static String getCarrierBIBSUid() {
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
// DebugScreen.Log("Util.getCarrierBIBSUid() for ippp--------->>" + records[currentRecord].getCid().toLowerCase());
if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
// DebugScreen.Log("Util.getCarrierBIBSUid() for bibs..........'''''" + records[currentRecord].getName().toLowerCase().indexOf("bibs") );
if (records[currentRecord].getName().toLowerCase().indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
return null;
}
public static String getAvailableConnectionsString() {
String conns = null;
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.getRecords();
String cid;
String uid;
for (int i = 0; i < records.length; i++) {
ServiceRecord myRecord = records[i];
// System.out.println("record name:"+myRecord.getName()+" cid:"+myRecord.getCid().toLowerCase()+" "+myRecord.getUid().toLowerCase());
if (myRecord.isValid() && !myRecord.isDisabled()) {
cid = myRecord.getCid().toLowerCase();
uid = myRecord.getUid().toLowerCase();
//Wap2.0
if (cid.indexOf("wptcp") != -1 && uid.indexOf("wifi") == -1 && uid.indexOf("mms") == -1 ) {
conns = ";deviceside=true" + ";ConnectionUID="+ myRecord.getUid();
if(myRecord.getUid().equalsIgnoreCase("GTCP BIBS")){
return conns;
}
}
}
}
return conns;
}
This code is work for me..
When I run this application on a device using the WiFi
it's working fine. But when I am using a mobile network or 3g it's giving an error.
It's not working on the mobile network.
I am using this code:
connection = (HttpConnection) Connector.open(APIURL+ updateConnectionSuffix());
And my ConnectionTools class code:
public String updateConnectionSuffix() {
String connSuffix;
if (DeviceInfo.isSimulator()) {
connSuffix = ";deviceside=true";
} else if ((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
&& RadioInfo.areWAFsSupported(RadioInfo.WAF_WLAN)) {
connSuffix = ";interface=wifi";
} else {
String uid = null;
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.findRecordsByCid("WPTCP");
for (int i = 0; i < records.length; i++) {
if (records[i].isValid() && !records[i].isDisabled()) {
if (records[i].getUid() != null
&& records[i].getUid().length() != 0) {
if ((records[i].getCid().toLowerCase().indexOf("wptcp") != -1)
&& (records[i].getUid().toLowerCase().indexOf(
"wifi") == -1)
&& (records[i].getUid().toLowerCase().indexOf(
"mms") == -1)) {
uid = records[i].getUid();
break;
}
}
}
}
if (uid != null) {
// WAP2 Connection
connSuffix = ";ConnectionUID=" + uid;
} else {
connSuffix = ";deviceside=true";
}
}
return connSuffix;
}
Can you give me any solutions?
What should we do for the mobile network or 3g?
Try this code.
public static String getConnectionString() {
String connectionString = null;
// Simulator behaviour is controlled by the USE_MDS_IN_SIMULATOR
// variable.
if (DeviceInfo.isSimulator()) {
connectionString = ";deviceside=true";
}
// Wifi is the preferred transmission method
else if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null) {
// Has carrier coverage, but not BIBS. So use the carrier's TCP
// network
connectionString = ";deviceside=true";
} else {
// otherwise, use the Uid to construct a valid carrier BIBS
// request
connectionString = ";deviceside=false;connectionUID="+carrierUid + ";ConnectionType=mds-public";
}
}
// Check for an MDS connection instead (BlackBerry Enterprise Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid hassling the user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
connectionString = "none";
}
// In theory, all bases are covered by now so this shouldn't be reachable.But hey, just in case ...
else {
connectionString = ";deviceside=true";
}
return connectionString;
}
/**
* Looks through the phone's service book for a carrier provided BIBS
* network
*
* #return The uid used to connect to that network.
*/
private synchronized static String getCarrierBIBSUid() {
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
if (records[currentRecord].getName().toLowerCase()
.indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
return null;
}
Replace this function by your updateConnectionSuffix().
Let me explain : - This is for connection using mobile network 2g or 3g any network" just copy & paste & enjoy
String url = "vm.b24esolution.com:9090";
final HttpConnection connection = (HttpConnection) Connector.open("socket://"+url+updateConnectionSuffix()+";apn=rim.net.gprs;tunnelauthusername =;tunnelauthpassword=",Connector.READ_WRITE);