Receiving data in serial port ESP8266 - webserver

I have sent data to a HTTP server (I have created the server with ESP8266) and the server gives the data completely.
But the problem is, when I refresh the web browser the data removed.
I don't know how can I have a backup of my data and every time I refresh the browser I can see the older data.
Here is my code:
#include <ESP8266WiFi.h>
const char* ssid = "Ashnay-E-Aval";
const char* password = "8841525252";
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
server.begin();
Serial.println("Server started");
Serial.println(WiFi.localIP());
}
void loop() {
WiFiClient client = server.available();
if (!client) {
return;
}
Serial.println("new client");
while (!client.available()) {
delay(1);
}
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();
String s;
String str=Serial.readStringUntil('\n');
s+= "<!DOCTYPE html>";
s+= "<html>";
s+= "<body>";
s+= "<h1>My First Heading</h1>";
s+= "<p>My "+STR+".</p>";
s+= "</body>";
s+= "</html>";
str="";
client.print(s);
delay(1);
Serial.println("Client disconnected");
}

If I understand you correctly, your ESP8266 gets some data (a string) over Serial from STM32. The ESP8266 may or may not get new data every execution of main loop. You want to update your website when there's new data (new string) from your STM32. If there's nothing sent, you want to display old data (old string).
In order to achieve that you need to:
Declare global variable, so it's not recreated every loop.
Compare that variable with new data from readStringUntil().
If the new data is not empty (STM32 sent something), then assign to the global variable new data.
Use the global variable to display data on the website.
Code:
#include <ESP8266WiFi.h>
const char* ssid = "Ashnay-E-Aval";
const char* password = "8841525252";
WiFiServer server(80);
String str = "";
void setup() {
Serial.begin(115200);
delay(10);
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
server.begin();
Serial.println("Server started");
Serial.println(WiFi.localIP());
}
void loop() {
WiFiClient client = server.available();
if (!client) {
return;
}
Serial.println("new client");
while (!client.available()) {
delay(1);
}
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();
String s;
String newStr = Serial.readStringUntil('\n');
if (!newStr.empty()) {
str = newStr;
}
s+= "<!DOCTYPE html>";
s+= "<html>";
s+= "<body>";
s+= "<h1>My First Heading</h1>";
s+= "<p>My "+STR+".</p>";
s+= "</body>";
s+= "</html>";
str="";
client.print(s);
delay(1);
Serial.println("Client disconnected");
}

Related

NodeMCU Unity Connection, using UDP

I am trying to connect NodeMCU with unity for my university project.
My nodemcu receives data (tested with a UDP test tool application). I will leave the code below.
But I have problems with Unity. I tried to find a simple example or something like that.
The code I found recently is simple enough, but it makes Unity freeze. I found it here and edited it a bit.
NodeMCU code in Arduino IDE
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
const char* ssid = "Epic SSID";
const char* password = "EpicPassword";
WiFiUDP Udp;
unsigned int port = 25666;
char packet[255];
IPAddress ip(192, 168, 43, 20);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
void setup()
{
Serial.begin(115200);
Serial.println();
WiFi.hostname("YVRB-01");
WiFi.config(ip, gateway, subnet);
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("Connection Successful");
Udp.begin(port);
Serial.printf("Listener started at IP %s, at port %d", WiFi.localIP().toString().c_str(), port);
}
void loop()
{
int packetSize = Udp.parsePacket();
if (packetSize)
{
Serial.printf("Received %d bytes from %s, port %d", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort());
int len = Udp.read(packet, 255);
if (len > 0)
{
packet[len] = 0;
}
Serial.printf("UDP packet contents: %s", packet);
Serial.println();
}
Udp.beginPacket (Udp.remoteIP(), Udp.remotePort());
Udp.write("Epic message");
Udp.endPacket();
delay(300);
}
When it worked, I took off my shirt and ran too kitchen.
My code in Unity
/*
C# Network Programming
by Richard Blum
Publisher: Sybex
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
public class udpsend : MonoBehaviour
{
Socket server;
IPEndPoint ipep;
void Start()
{
byte[] data = new byte[1024];
ipep = new IPEndPoint(
IPAddress.Parse("192.162.43.209"), 25666);
server = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
string welcome = "I am connected";
data = Encoding.ASCII.GetBytes(welcome);
server.SendTo(data, data.Length, SocketFlags.None, ipep);
}
void Update()
{
string input, stringData;
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)sender;
byte[] data = new byte[1024];
int recv = server.ReceiveFrom(data, ref Remote);
Console.WriteLine("Message received from {0}:", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
//while (true)
//{
// input = Console.ReadLine();
// if (input == "exit")
// break;
// server.SendTo(Encoding.ASCII.GetBytes(input), Remote);
// data = new byte[1024];
// recv = server.ReceiveFrom(data, ref Remote);
// stringData = Encoding.ASCII.GetString(data, 0, recv);
// Console.WriteLine(stringData);
//}
Console.WriteLine("Stopping client");
server.Close();
}
public void SendData(string message)
{
byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(message);
server.SendTo(data, data.Length, SocketFlags.None, ipep);
}
}
I'm just saying that I don't fully understand, but I edited a little bit.
Any fixes or code examples will be appreciated. I just want a method that I can call like SendData("Never gonna give you up!").
I can now transfer information from the Unity app to NodeMCU and from NodeMCU to Unity!
All the code is below.
I used the code and edited the a bit.
To receive data, I used this code right here.
To send information, I used this code and like a "mash up" this code together to create one program that can send and receive.
The reason I have done this is that there were a conflict, because there were one client and multiple codes trying to access it.
For Node MCU I used this code which is pretty much the same as I wrote in question above.
I also made manager code using which I can send message and do other stuff.
It is also important to close all the ports or else Unity will freeze (a very annoying thing).
Nodemcu code in the Arduino IDE:
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
const char* ssid = "YVRB";
const char* password = "YGreater";
WiFiUDP Udp;
unsigned int port = 25666;
char packet[255];
IPAddress ip(192, 168, 43, 20);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
void setup()
{
Serial.begin(115200);
Serial.println();
WiFi.hostname("YVRB-01");
WiFi.config(ip, gateway, subnet);
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("Connection Successful");
Udp.begin(port);
Serial.printf("Listener started at IP %s, at port %d", WiFi.localIP().toString().c_str(), port);
Serial.println();
}
void loop()
{
int packetSize = Udp.parsePacket();
if (packetSize)
{
Serial.printf("Received %d bytes from %s, port %d", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort());
int len = Udp.read(packet, 255);
if (len > 0)
{
packet[len] = 0;
}
Serial.printf("UDP packet contents: %s", packet);
Serial.println();
}
Udp.beginPacket (Udp.remoteIP(), Udp.remotePort());
Udp.write("Important data");
Udp.endPacket();
delay(300);
}
File UDPSend.cs code which receives as well:
// Inspired by this thread: https://forum.unity.com/threads/simple-udp-implementation-send-read-via-mono-c.15900/
// Thanks OP la1n
// Thanks MattijsKneppers for letting me know that I also need to lock my queue while enqueuing
// Adapted during projects according to my needs
using UnityEngine;
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class UDPSend
{
public string IP { get; private set; }
public int sourcePort { get; private set; } // Sometimes we need to define the source port, since some devices only accept messages coming from a predefined sourceport.
public int remotePort { get; private set; }
IPEndPoint remoteEndPoint;
Thread receiveThread;
// udpclient object
UdpClient client;
// public
// public string IP = "127.0.0.1"; default local
public int port = 25666; // define > init
// Information
public string lastReceivedUDPPacket = "";
public string allReceivedUDPPackets = ""; // Clean up this from time to time!
public bool newdatahereboys = false;
public void init(string IPAdress, int RemotePort, int SourcePort = -1) // If sourceport is not set, its being chosen randomly by the system
{
IP = IPAdress;
sourcePort = SourcePort;
remotePort = RemotePort;
remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), remotePort);
if (sourcePort <= -1)
{
client = new UdpClient();
Debug.Log("Sending to " + IP + ": " + remotePort);
}
else
{
client = new UdpClient(sourcePort);
Debug.Log("Sending to " + IP + ": " + remotePort + " from Source Port: " + sourcePort);
}
receiveThread = new Thread(
new ThreadStart(ReceiveData));
receiveThread.IsBackground = true;
receiveThread.Start();
}
private void ReceiveData()
{
//client = sender.client;
while (true)
{
try
{
// Bytes empfangen.
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = client.Receive(ref anyIP);
// Bytes mit der UTF8-Kodierung in das Textformat kodieren.
string text = Encoding.UTF8.GetString(data);
// Den abgerufenen Text anzeigen.
Debug.Log(text);
newdatahereboys = true;
//PlayerPrefs.SetString("ReceivedData", text);
// Latest UDPpacket
lastReceivedUDPPacket = text;
// ....
allReceivedUDPPackets = allReceivedUDPPackets + text;
}
catch (Exception err)
{
Debug.Log(err.ToString());
}
}
}
// sendData in different ways. Can be extended accordingly
public void sendString(string message)
{
try
{
byte[] data = Encoding.UTF8.GetBytes(message);
client.Send(data, data.Length, remoteEndPoint);
}
catch (Exception err)
{
Debug.Log(err.ToString());
}
}
public void sendInt32(Int32 myInt)
{
try
{
byte[] data = BitConverter.GetBytes(myInt);
client.Send(data, data.Length, remoteEndPoint);
}
catch (Exception err)
{
Debug.Log(err.ToString());
}
}
public void sendInt32Array(Int32[] myInts)
{
try
{
byte[] data = new byte[myInts.Length * sizeof(Int32)];
Buffer.BlockCopy(myInts, 0, data, 0, data.Length);
client.Send(data, data.Length, remoteEndPoint);
}
catch (Exception err)
{
Debug.Log(err.ToString());
}
}
public void sendInt16Array(Int16[] myInts)
{
try
{
byte[] data = new byte[myInts.Length * sizeof(Int16)];
Buffer.BlockCopy(myInts, 0, data, 0, data.Length);
client.Send(data, data.Length, remoteEndPoint);
}
catch (Exception err)
{
Debug.Log(err.ToString());
}
}
public string getLatestUDPPacket()
{
allReceivedUDPPackets = "";
return lastReceivedUDPPacket;
}
public void ClosePorts()
{
Debug.Log("closing receiving UDP on port: " + port);
if (receiveThread != null)
receiveThread.Abort();
client.Close();
}
}
File manager.cs:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class manager : MonoBehaviour {
public int Remoteport = 25666;
public UDPSend sender = new UDPSend();
public string datafromnode;
void Start()
{
sender.init("192.168.43.209", Remoteport, 25666);
sender.sendString("Hello from Start. " + Time.realtimeSinceStartup);
Application.targetFrameRate = 60;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyUp(KeyCode.Return))
sender.sendString("This should be delivered");
if (sender.newdatahereboys)
{
datafromnode = sender.getLatestUDPPacket();
}
}
public void OnDisable()
{
sender.ClosePorts();
}
public void OnApplicationQuit()
{
sender.ClosePorts();
}
}
Success! See justlookatem.

Xamarin Forms Socket connection using IPV6 address

I have a sample Socket application that communicates between two devices using and IP address and port. The IPV4 IP-addresses work fine in the application but I cannot seem to get the correct information for the IPV6 IP-addresses.
I believe I understand what is being talked about in this article with regarding to the Zone ID for an IPV6 address
https://howdoesinternetwork.com/2013/ipv6-zone-id
and I also believe I understand what is being said here within that document:
If you want to ping a neighbor computer, you will need to specify the neighbor’s IPv6 Link-Local address plus the Zone ID of your computer’s network adapter that is going towards that computer.
i.e. I need to use the remote IPV6 address with the local device's Zone ID.
My problem is I cannot seem to figure out what the local device's (ios, android) Zone ID is for IPV6 addresses. I have uploaded my sample Xamarin Forms socket server and client code to GitHub and it can be accessed here.
Server Code: https://github.com/gceaser/AsyncSocket
Client Code: https://github.com/gceaser/AsyncSocketClient
I have the IP Addresses and ports defined in the App.xaml.cs for each project and a switch in each project to go back and forth between an IP V4 and V6 connection. (You should update the IP Addresses for your environment if you are trying to test this.) The V4 connection works but I cannot get the V6 connection to work. Any help would be greatly appreciated.
NOTE: To the best of my knowledge you cannot run the client and server on the same windows machine. Something weird about sockets not being able to communicate that way as I have document in one of my other StackOverflow post. Thus to test please run the server on a Windows box and the Client within iOS.
UPDATE:
Here is the code for the Server Socket connection:
using System;
using
System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;
using System.Collections.Generic;
namespace AsyncSocketServer
{
public class AsynchronousSocketListener
{
public static ManualResetEvent allDone = new ManualResetEvent(false);
public delegate void onMessageReceivedComplete(object sender, string message);
public delegate void onResponseMessageSent(object sender, string message);
public static event onMessageReceivedComplete MessageReceivedComplete;
public static event onResponseMessageSent ResponseMessageSent;
public AsynchronousSocketListener()
{
}
public async static Task StartListening(IPAddress pobj_IPAddress, int pi_Port)
{
try
{
//IPAddress ipAddress = IPAddress.Parse(pobj_IPAddress);
IPEndPoint localEndPoint = new IPEndPoint(pobj_IPAddress, pi_Port);
Socket listener = new Socket(pobj_IPAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
listener.Bind(localEndPoint);
listener.Listen(100);
//ViewModelObjects.AppSettings.SocketStatus = ge_SocketStatus.e_Listening;
await Task.Delay(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Debug.WriteLine("Waiting for a connection on " + pobj_IPAddress + " at port " + pi_Port.ToString() + "...");
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
Debug.WriteLine("StartListening Error" + e.ToString());
}
Debug.WriteLine("Read To end class");
}
public static void AcceptCallback(IAsyncResult ar)
{
try
{
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
//If we have shut down the socket dont do this.
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
catch (Exception e)
{
Debug.WriteLine("AcceptCallback Error" + e.ToString());
}
}
public static void ReadCallback(IAsyncResult ar)
{
try
{
string ls_ReceivedCommunicationContent = string.Empty;
string ls_ReturnCommunicationContent = string.Empty;
//string content = string.Empty;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
ls_ReceivedCommunicationContent = state.sb.ToString();
if (ls_ReceivedCommunicationContent.IndexOf("<EOF>") > -1)
{
//We need to take off the end of file marker
string ls_WorkContent = ls_ReceivedCommunicationContent.Replace("<EOF>", "");
ls_ReturnCommunicationContent = ls_WorkContent;
//Different than app
Device.BeginInvokeOnMainThread(() => {
MessageReceivedComplete(null, ls_WorkContent);
});
Send(handler, ls_ReturnCommunicationContent);
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
}
catch (Exception e)
{
Debug.WriteLine("ReadCallback Error" + e.ToString());
}
}
private static void Send(Socket handler, String data)
{
try
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
Device.BeginInvokeOnMainThread(() => {
ResponseMessageSent(null, data);
});
}
catch (Exception e)
{
Debug.WriteLine("Send Error" + e.ToString());
}
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Debug.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Debug.WriteLine("SendCallback Error" + e.ToString());
}
}
}
}
Here is the client Code:
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace AsyncSocketClient
{
// This template use base socket syntax to change Pattern. (like Send, Receive, and so on)
// Convert to Task-based Asynchronous Pattern. (TAP)
public static class AsynchronousClientSocket
{
public static async Task<string> SendMessage(string ps_IPAddress, int pi_Port, string ps_Message)
{
string ls_response = "";
try
{
string ls_ReturnMessage = "";
// Establish the remote endpoint for the socket.
IPAddress ipAddress = IPAddress.Parse(ps_IPAddress);
IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, pi_Port);
// Create a TCP/IP socket.
var client = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
var isConnect = await client.ConnectAsync(remoteEndPoint).ConfigureAwait(false);
if (!isConnect)
{
Console.WriteLine("Can not connect.");
return ls_ReturnMessage;
}
// Send test data to the remote device.
var bytesSent = await client.SendAsync(ps_Message + "<EOF>").ConfigureAwait(false);
Console.WriteLine("Sent {0} bytes to server.", bytesSent);
// Receive the response from the remote device.
ls_response = await client.ReceiveAsync().ConfigureAwait(false);
// Write the response to the console.
Console.WriteLine("Response received : {0}", ls_response);
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
}
catch (Exception ex)
{
Debug.WriteLine("Error: " + ex.Message);
}
return ls_response;
}
private static Task<bool> ConnectAsync(this Socket client, IPEndPoint remoteEndPoint)
{
if (client == null) throw new ArgumentNullException(nameof(client));
if (remoteEndPoint == null) throw new ArgumentNullException(nameof(remoteEndPoint));
return Task.Run(() => Connect(client, remoteEndPoint));
}
private static bool Connect(this Socket client, EndPoint remoteEndPoint)
{
if (client == null || remoteEndPoint == null)
return false;
try
{
client.Connect(remoteEndPoint);
return true;
}
catch (Exception)
{
return false;
}
}
private static async Task<string> ReceiveAsync(this Socket client, int waitForFirstDelaySeconds = 3)
{
if (client == null) throw new ArgumentNullException(nameof(client));
// Timeout for wait to receive and prepare data.
for (var i = 0; i < waitForFirstDelaySeconds; i++)
{
if (client.Available > 0)
break;
await Task.Delay(1000).ConfigureAwait(false);
}
// return null If data is not available.
if (client.Available < 1)
return null;
// Size of receive buffer.
const int bufferSize = 1024;
var buffer = new byte[bufferSize];
// Get data
var response = new StringBuilder(bufferSize);
do
{
var size = Math.Min(bufferSize, client.Available);
await Task.Run(() => client.Receive(buffer)).ConfigureAwait(false);
response.Append(Encoding.ASCII.GetString(buffer, 0, size));
} while (client.Available > 0);
// Return result.
return response.ToString();
}
private static async Task<int> SendAsync(this Socket client, string data)
{
var byteData = Encoding.ASCII.GetBytes(data);
return await SendAsync(client, byteData, 0, byteData.Length, 0).ConfigureAwait(false);
}
private static Task<int> SendAsync(this Socket client, byte[] buffer, int offset,
int size, SocketFlags socketFlags)
{
if (client == null) throw new ArgumentNullException(nameof(client));
return Task.Run(() => client.Send(buffer, offset, size, socketFlags));
}
}
}
When I start the serer, switch it to IPV6 and start it, I get the message that it is waiting for a connection as follows:
Waiting for a connection on fe80::cda4:ea52:29f5:2c7c at port 8080...
When I start the Client, switch it to IPV6 and attempt to send a message, I get the error:
2020-06-19 09:32:51.029902-0400 AsyncSocketClient.iOS[33593:9360848] Can not connect.

simcard message trans/receiver simulator

We have a project that we should send message to a huge number of sim cards (more than 1 Million) and receive and handle answers.
For testing this, I am using Selenium SMPPSim to simulate sending a message.
this is work fine for sending messages. and with enabling callback server I can receive messages that I send on another port.
But my question is how can I send back a message to SMPP server?
I am using EasySMPP library for connecting to smpp server
My SMPP Server Code:
private SMPPClient _client;
private readonly object _lockObject = new object();
public SMPPClient GetClient()
{
if (_client != null)
{
return _client;
}
lock (_lockObject)
{
_client = new SMPPClient();
var smsc = new SMSC
{
Host = "127.0.0.1",
Port = 2775,
SystemId = "smppclient1",
Password = "password",
SourceTon = 5,
SourceNpi = 1,
AddrTon = 1,
AddrNpi = 1,
SystemType = "8945",
};
_client.OnDeliverSm += Client_OnDeliverSm;
Console.WriteLine("Client_OnDeliverSm added");
_client.OnSubmitSmResp += Client_OnSubmitSmResp;
Console.WriteLine("OnSubmitSmResp added");
_client.AddSMSC(smsc);
if (!_client.Connect())
throw new Exception($"Can not connect to smpp link: {smsc.Host} : {smsc.Port}");
return _client;
}
}
public void SendByCampaignItemId()
{
var smppClient = GetClient();
lock (smppClient)
{
var msgId = smppClient.SubmitSM(1, 1, "339123456789", 1, 1, "339632587436",
0x40, // EsmClass.UdhIndicator
0x7f, // protocol identifier
0, // priority flag level 0
DateTime.MinValue,
DateTime.MinValue,
// DateTime.Now.AddMinutes(10),
//DateTime.Now.AddHours(3),
(byte)DeliveryReportType.AlwaysSendDeliveryReport,
0x00, //replace if present
0xf6, // data coding
0, // default msg id
new byte[] { 0x02,0x70,0x00,0x34,0x77,0x88,0x99,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF});
}
}
private void Client_OnSubmitSmResp(SubmitSmRespEventArgs e)
{
Console.WriteLine("Submit Received");
}
private void Client_OnDeliverSm(DeliverSmEventArgs e)
{
Console.WriteLine("Deliver Received");
}
And here is my code which listens to port 3333:
static void Main(string[] args)
{
TcpListener server = null;
try
{
Int32 port = 3333;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
server = new TcpListener(localAddr, port);
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
while (true)
{
Console.Write("Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
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);
Console.WriteLine("Received: {0}", data);
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
stream.Write(msg, 0, msg.Length);
//WHAT SHOULD I DO HERE SO THAT I CAN SEND BACK A MESSAGE (DELIVER SM) TO SMPP SIM??!!!
Console.WriteLine("Sent: {0}", data);
}
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
And my SMPPSIM Config file :
SMPP_PORT=2775
SMPP_CONNECTION_HANDLERS=10
CONNECTION_HANDLER_CLASS=com.seleniumsoftware.SMPPSim.StandardConnectionHandler
PROTOCOL_HANDLER_CLASS=com.seleniumsoftware.SMPPSim.StandardProtocolHandler
LIFE_CYCLE_MANAGER=com.seleniumsoftware.SMPPSim.LifeCycleManager
MESSAGE_STATE_CHECK_FREQUENCY=5000
MAX_TIME_ENROUTE=10000
DELAY_DELIVERY_RECEIPTS_BY=0
PERCENTAGE_THAT_TRANSITION=75
PERCENTAGE_DELIVERED=90
PERCENTAGE_UNDELIVERABLE=6
PERCENTAGE_ACCEPTED=2
PERCENTAGE_REJECTED=2
DISCARD_FROM_QUEUE_AFTER=60000
HTTP_PORT=88
HTTP_THREADS=1
DOCROOT=www
AUTHORISED_FILES=/css/style.css,/index.htm,/inject_mo.htm,/favicon.ico,/images/logo.gif,/images/dots.gif,/user-guide.htm,/images/homepage.gif,/images/inject_mo.gif
INJECT_MO_PAGE=/inject_mo.htm
SYSTEM_IDS=smppclient1,smppclient2
PASSWORDS=password,password
OUTBIND_ENABLED=false
OUTBIND_ESME_IP_ADDRESS=127.0.0.1
OUTBIND_ESME_PORT=2776
OUTBIND_ESME_SYSTEMID=smppclient1
OUTBIND_ESME_PASSWORD=password
DELIVERY_MESSAGES_PER_MINUTE=0
DELIVER_MESSAGES_FILE=deliver_messages.csv
LOOPBACK=TRUE
ESME_TO_ESME=false
OUTBOUND_QUEUE_MAX_SIZE=1000
INBOUND_QUEUE_MAX_SIZE=1000
DELAYED_INBOUND_QUEUE_PROCESSING_PERIOD=60
DELAYED_INBOUND_QUEUE_MAX_ATTEMPTS=100
DECODE_PDUS_IN_LOG=true
CAPTURE_SME_BINARY=false
CAPTURE_SME_BINARY_TO_FILE=sme_binary.capture
CAPTURE_SMPPSIM_BINARY=false
CAPTURE_SMPPSIM_BINARY_TO_FILE=smppsim_binary.capture
CAPTURE_SME_DECODED=false
CAPTURE_SME_DECODED_TO_FILE=sme_decoded.capture
CAPTURE_SMPPSIM_DECODED=false
CAPTURE_SMPPSIM_DECODED_TO_FILE=smppsim_decoded.capture
CALLBACK=true
CALLBACK_ID=SIM1
CALLBACK_TARGET_HOST=localhost
CALLBACK_PORT=3333
DELIVER_SM_INCLUDES_USSD_SERVICE_OP=false
DELIVERY_RECEIPT_OPTIONAL_PARAMS=true
DELIVERY_RECEIPT_TLV=1403/0A/34343132333435363738
SMSCID=SMPPSim
SIMULATE_VARIABLE_SUBMIT_SM_RESPONSE_TIMES=false
And another question:
If SMPPSim is not a good choice for my work, what else can i use?
UPDATE 1:
I look a little more and I think I find a simpler question.
assume that i have to SMPPSims.
How can I send message from a SMPPSim to another one?

ESP8266: Send client.remoteIP() to client

`ESP8266 Web server will not send client.remoteIP() to client browser.
void loop() {
// Listenning for new clients
WiFiClient client = server.available();
if (client) {
Serial.println("New client");
// bolean to locate when the http request ends
boolean blank_line = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
if (c == '\n' && blank_line) {
getWeather();
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
client.println();
// your actual web page that displays temperature
client.println("<!DOCTYPE HTML>");
client.println("<html>");
//client.println("<head><META HTTP-EQUIV=\"refresh\" CONTENT=\"15\"></head>");
client.println("<body><h1>ESP8266 Weather Web Server</h1>");
client.println("<table border=\"2\" width=\"456\" cellpadding=\"10\"><tbody><tr><td>");
client.println();
client.println(client.remoteIP());
client.println();
client.println("<h3>Temperature = ");
client.println(temperatureFString);
client.println("°F</h3><h3>Humidity = ");
client.println(humidityString);
client.println("%</h3><h3>Approx. Dew Point = ");
client.println(dpString);
client.println("°F</h3><h3>Pressure = ");
client.println(pressureString);
client.println("hPa (");
client.println(pressureInchString);
client.println("Inch)</h3></td></tr></tbody></table></body></html>");
int x;
for(x = 1;x < 2; x++)
{
Serial.println(client.remoteIP());
}
break;
}
if (c == '\n') {
// when starts reading a new line
blank_line = true;
}
else if (c != '\r') {
// when finds a character on the current line
blank_line = false;
}
}
}
// closing the client connection
delay(1);
client.stop();
Serial.println("Client disconnected.");
}
Is there a way that the client's IP can be displayed in the table of browser?
I have no problem doing a Serial.print(client.remoteIP()).
IPAddress is a class and does not return a String. Better to use in that fashion for your case :
client.remoteIP().toString().c_str()

java.net.UnknownHostException: cs.xfire.com

I am trying to establish a connection from an android xfire client, its a TCP connection I believe. I have googled everywhere and it has been said over and over again to use cs.xfire.com on port 25999 to connect to xfire (a messaging service). But at the end I get an exception saying it doesnt connect. So I would like to know why can I not establish a connection. There is almost no information on the internet that would help me figure out why it won't connect, I have listened to the connection via packet sniffers and they have given me port 25999 aswell right when I click on "connect" from the official xfire windows app. So I am really confused, sorry if this question is not making much sense, here is the code of what I have:
public class Connectionn extends Activity{
private DataInputStream in = null;
private DataOutputStream out = null;
private byte[] buffer;
private String username, password, nickname, statustext = "Online";
private boolean runThread = true;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connected);
TextView txtView1 = (TextView) findViewById(R.id.tvTest);
Bundle extras = getIntent().getExtras();
String username = extras.getString("username");
String password = extras.getString("password");
try {
Socket s = new Socket("cs.xfire.com", 25999);
txtView1.setText("Connected!");
in = new DataInputStream(s.getInputStream());
out = new DataOutputStream(s.getOutputStream());
login();
} catch (IOException ioe) {
//disconnect();
txtView1.setText(ioe.toString());
}
}
public void run() {
setTitle("Xfire Reader Thread");
while(runThread) {
readBytes();
debug(buffer);
switch(buffer[0] & 0xFF) {
case 0x80: // salt
break;
case 0x81: // auth failed
disconnect();
break;
case 0x82: // loginreply
break;
case 0x83: // friendslist
break;
case 0x84: // friend online
break;
case 0x85: // receive message
/*ReceiveMessagePacket rmp = new ReceiveMessagePacket(buffer);
if (rmp.getMessageType() == ReceiveMessagePacket.MSGTYPE_IM) {
AckImPacket amp =
new AckImPacket(rmp.getSid(), rmp.getImIndex());
write(amp.getBytes());
}*/
break;
case 0x87: // friend in game
break;
case 0x91: // disconnected with reason
disconnect();
break;
case 0x9a: // friend status text
break;
case 0xac:
break;
}
}
}
private void login() {
// TODO Auto-generated method stub
// initialize connection with the 'UA01' packet
write("UA01".getBytes());
// send the version packet
final byte[] p_version_1 = new byte[] {
0x03, 0, 0x01, 0x07,
0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, // version
0x02
};
final int version = 118;
String vp = null;
write(vp.getBytes());
// start the reader thread
onStart();
}
public void disconnect() {
//EventManager.removeObserver(this);
runThread = false;
try {
out.write(new byte[] { 0, 0, 0, 0 }); // sabotage the stream
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
out.close();
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
//FriendManager.getInstance().cleanup();
// EventManager.fireEvent(new DatalessEvent(XfireEvent.XF_OFFLINE));
}
}
private void readBytes() {
try {
byte[] numBytes = new byte[2];
in.read(numBytes, 0, 2);
int low = numBytes[0] & 0xFF, high = numBytes[1] & 0xFF;
int len = (0x00 | low | (high << 8)) - 2;
if (len <= 0) {
buffer = new byte[] { 0 };
return;
}
buffer = new byte[len];
in.read(buffer, 0, len);
} catch (IOException ioe) {
ioe.printStackTrace();
disconnect();
}
}
private static void debug(byte[] bs) {
for (byte b : bs) {
System.out.print(String.format("%02x", b) + " ");
}
System.out.println();
}
public void write(byte[] bs) {
try {
out.write(bs);
} catch (IOException ioe) {
ioe.printStackTrace();
disconnect();
}
}
}
I get an exception saying it doesn't connect
No you don't. Read it again. It's in your title. It says 'unknown host'. That's not a connect failure: it's a lookup failure. Either cs.xfire.com doesn't exist or it isn't known to your DNS.