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();
}
}
Related
i bought a NP-05B powerUSB device and am trying to interface the device in c#. I was able to connect to the device using YAT.
YAT interface response
In the c# form i imported a serial device and i am able to connect and send commands to the device. But when the device answers to the command it only returns: pshow. The serial read seems to not be able to catch "CR NUL LF" and anything afterward.
Here is my serialRead implementation
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int Count;
Byte[] Rx_Byte;
Count = 0;
Rx_Byte = new Byte[serialPort1.BytesToRead];
serialPort1.Read(Rx_Byte, 0, Rx_Byte.Length);
while (Count < Rx_Byte.Length)
{
if (Rx_Byte[Count] != 0x00)
{
Console.WriteLine("receiving " + Rx_Byte[Count].ToString());
}
Count++;
}
}
and here is the response i get from my console:
Console Output
Thank you for your time.
With a serial sniffer i was able to figure out that i needed to send a return carriage and that C# doesn't send one by default when writing to serial port
thank you.
I need to transfer file (xml) to AS2 server. I am not so good at this communication channel, but I need to do it programmatically. For example sending to SFTP I am using this code:
import com.jcraft.jsch.*;
.......
public void uploadViaSFTP (String fileToUpload, String sftp_host, String sftp_user, String sftp_psw)
{
int SFTPPORT = 22;
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
try{
JSch jsch = new JSch();
session = jsch.getSession(sftp_user,sftp_host,SFTPPORT);
session.setPassword(sftp_psw);
java.util.Properties config = new java.util.Properties();
//this line should be used only for testing, not for production
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp)channel;
channelSftp.cd("/");
File f = new File(fileToUpload);
channelSftp.put(new FileInputStream(f), f.getName());
}catch(Exception ex){
ex.printStackTrace();
}
}
But now I need to do same for AS2. What library I could use (openAS2)? Is there a simple method to transfer like it does for SFTP?
You should be able to use standard HTTPS components and S/MIME attachment, since AS2 is a security layer and usage specification on top of HTTP or HTTPS.
I'd start with (https://www.mkyong.com/java/java-https-client-httpsurlconnection-example/), the AS2 specification (http://www.ietf.org/rfc/rfc4130.txt) , and this example from github: (https://github.com/protocol7/smime-java-example)
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.
I need to get the user's local IP for my ASP.NET application and I'm using this method:
protected string GetIPAddress()
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}
}
return context.Request.ServerVariables["REMOTE_ADDR"];
}
However, when I publish my website I always get 192.168.2.1 no matter where the user is opening the website from.
Does anyone know how to solve this issue?
Some network devices make use of the X-forwarded-for header. You should check if the requests hitting your application have this header.
You can get the client's IP address from HTTP_X_FORWARDED_FOR or REMOTE_ADDR.
var ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ipAddress ))
{
ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
return ipAddress;
http://searchnetworking.techtarget.com/definition/time-to-live
From this article, im Confused about the defanition about this subject.
is there any chance someone help me undestand better whats going on?
stav.
----------------------------------
EDIT:
i tried to send massage to my self from the same computer.
when i set the TTL value to 0, the pack i send still get to me. why is that?
here is the code:
btw,this line in the Send Method.
server.SetSocketOption(SocketOptionLevel.IP,
SocketOptionName.MulticastTimeToLive, 0);
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
class MAIN
{
public static MulticastOption MulticastOption;
private static MulticastOption CreateGroup()
{
MulticastOption = new MulticastOption(IPAddress.Parse("224.100.0.1"));
return MulticastOption;
}
private static void Receive()
{
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
EndPoint ep = (EndPoint)iep;
sock.Bind(iep);
sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, MulticastOption);
//
byte[] data = new byte[1024];
new Thread(new ThreadStart(Send)).Start();
int recv = sock.ReceiveFrom(data, ref ep);
String stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString());
sock.Close();
}
private static void Send()
{
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9051);
IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050);
server.Bind(iep);
server.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("224.100.0.1")));
server.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.MulticastTimeToLive, 0);
server.SendTo(Encoding.ASCII.GetBytes("This is a test message"), iep2);
server.Close();
}
public static void Main(String[] args)
{
CreateGroup();
Receive();
Console.ReadKey();
}
}
Client machines set the TTL value when a packet is generated, to indicate the maximum number of hops the packet is permitted to go through.
Each time a packet passes through a router the router will decrement the TTL value.
If the TTL value reaches zero, the router will drop the packet and return an ICMP "hop count exceeded" error message.
The main benefit of the TTL field is to stop packets bouncing around forever in the event of a routing loop, i.e. a network fault that causes packets to bounce around and around between the same set of routers.