I have two applications: c++ service and a RoR web server (they are both running at same VPS)
I need to "send" some variables (and then do something with them) from each other. For exaple, i'm looking for something like this:
// my C++ sample
void SendMessage(string message) {
SendTo("127.0.0.1", message);
}
void GetMessage(string message) {
if (message == "stop")
SendMessage("success");
}
# Ruby sample
# application_controller.rb
def stop
#m = Messager.new
#m.send("stop")
end
I have never used it before, and i even don't know which technology should i search and learn.
Ok, i have found the solution. Its TCP sockets:
Ruby TCP server, to send messages:
require 'socket'
server = TCPServer.open(2000)
loop {
Thread.start(server.accept) do |client|
client.puts(Time.now.ctime)
client.puts "Closing the connection. Bye!"
client.close
end
}
Ruby client, to accept messages:
require 'socket'
host = 'localhost'
port = 2001 # it should be running server, or it will be connection error
s = TCPSocket.open(host, port)
while line = s.gets
puts line.chop
end
s.close
Now you should write TCP-server+client in another application. But you have got the idea.
Related
I was trying to connect a NodeMCU Socket client program to a Python server program, but I was not able to establish a connection.
I tested a simple Python client server code and it worked well.
Python Server Code
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
print c.recv(1024)
c.send('Thank you for connecting')
c.close() # Close the connection
Python client code (with this I tested the above code)
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.connect((host, port))
s.send('Hi i am aslam')
print s.recv(1024)
s.close # Close the socket when done
The output server side was
Got connection from ('192.168.99.1', 65385)
Hi i am aslam
NodeMCU code
--set wifi as station
print("Setting up WIFI...")
wifi.setmode(wifi.STATION)
--modify according your wireless router settings
wifi.sta.config("xxx", "xxx")
wifi.sta.connect()
function postThingSpeak()
print("hi")
srv = net.createConnection(net.TCP, 0)
srv:on("receive", function(sck, c) print(c) end)
srv:connect(12345, "192.168.0.104")
srv:on("connection", function(sck, c)
print("Wait for connection before sending.")
sck:send("hi how r u")
end)
end
tmr.alarm(1, 1000, 1, function()
if wifi.sta.getip() == nil then
print("Waiting for IP address...")
else
tmr.stop(1)
print("WiFi connection established, IP address: " .. wifi.sta.getip())
print("You have 3 seconds to abort")
print("Waiting...")
tmr.alarm(0, 3000, 0, postThingSpeak)
end
end)
But when I run the NodeMCU there is no response in the Python server.
The Output in the ESPlorer console looks like
Waiting for IP address...
Waiting for IP address...
Waiting for IP address...
Waiting for IP address...
Waiting for IP address...
Waiting for IP address...
WiFi connection established, IP address: 192.168.0.103
You have 3 seconds to abort
Waiting...
hi
Am I doing something wrong or missing some steps here?
Your guidance is appreciated.
After I revisited this for the second time it finally clicked. I must have scanned your Lua code too quickly the first time.
You need to set up all event handlers (srv:on) before you establish the connection. They may not fire otherwise - depending on how quickly the connection is established.
srv = net.createConnection(net.TCP, 0)
srv:on("receive", function(sck, c) print(c) end)
srv:on("connection", function(sck)
print("Wait for connection before sending.")
sck:send("hi how r u")
end)
srv:connect(12345,"192.168.0.104")
The example in our API documentation is wrong but it's already fixed in the dev branch.
I have a Java client, which obtains an autogenerated port. After starting the actor system, I want to access the port.
Config clientConfig = ConfigFactory.parseString("akka.remote.netty.tcp.port = 0")
.withFallback(ConfigFactory.parseString("akka.remote.netty.tcp.hostname = " + serverHostName))
.withFallback(ConfigFactory.load("common"));
actorSystem = ActorSystem.create("clientActorSystem", clientConfig);
// how to access the generated port here..!?
The port must already be set since the log output after ActorSystem.create(...) is like that:
[INFO] [03/31/2016 14:11:32.042] [main] [akka.remote.Remoting] Starting remoting
[INFO] [03/31/2016 14:11:32.233] [main] [akka.remote.Remoting] Remoting started; listening on addresses :[akka.tcp://actorSystem#localhost:58735]
[INFO] [03/31/2016 14:11:32.234] [main] [akka.remote.Remoting] Remoting now listens on addresses: [akka.tcp://actorSystem#localhost:58735]
If I try to get it via the configuration with actorSystem.settings().config().getValue("akka.remote.netty.tcp.port"), I still get 0 as defined before.
Has anyone an idea how this port (58735 in the example) can be accessed?
Using scala you can get Option of port on which Actor system is currently running:
val port = system.provider.getDefaultAddress.port
Hope you will be able to get the same code in Java.
The accepted answer probably worked for older versions of Akka but as of now (version 2.5.x) you will be getting something like:
Error:(22, 18) method provider in trait ActorRefFactory cannot be accessed in akka.actor.ActorSystem
The solution would be to use akka extensions. Here is how I use it:
Example. scala
package example
import akka.actor._
class AddressExtension(system: ExtendedActorSystem) extends Extension {
val address: Address = system.provider.getDefaultAddress
}
object AddressExtension extends ExtensionId[AddressExtension] {
def createExtension(system: ExtendedActorSystem): AddressExtension = new AddressExtension(system)
def hostOf(system: ActorSystem): String = AddressExtension(system).address.host.getOrElse("")
def portOf(system: ActorSystem): Int = AddressExtension(system).address.port.getOrElse(0)
}
object Main extends App {
val system = ActorSystem("Main")
println(AddressExtension.portOf(system))
}
I have a simulation where two modules UDPBasicApp (a client and a server) are connected together via an Ethernet link. Instead, I want that they be connected together through a wireless channel. The network is defined by the following NED file:
package udpbasic;
import inet.networklayer.autorouting.ipv4.IPv4NetworkConfigurator;
import inet.nodes.ethernet.Eth10M;
import inet.nodes.inet.StandardHost;
network ClientServer
{
#display("bgb=380,247");
submodules:
client: StandardHost
{
#display("p=84,100");
}
server: StandardHost
{
#display("p=278,100");
}
configurator: IPv4NetworkConfigurator
{
#display("p=181,188");
}
connections:
client.ethg++ <--> Eth10M <--> server.ethg++;
}
I know that I have to change the line
client.ethg++ <--> Eth10M <--> server.ethg++;
where the Ethernet link is defined. Can I connect the client and the server trough
a wireless link? Obviously, I am looking for the most basic configuration.
I am new in OMNeT++ and INET; I have searched the INET API reference, and it doesn't
help so much. I would thank any suggestion.
I recommend reading the wireless tutorial in INET 3.0.
https://github.com/inet-framework/inet/blob/master/tutorials/wireless/omnetpp.ini
Ini file:
[General]
# Some global configuration to make the model simpler
# At this point you should take a look at the NED files corresponding to this Ini file.
# They are rather simple. The only interesting thing is that they are using parametrized types
# (i.e. like) so we will be able to change the type of the different modules from the Ini file.
# This allows us go through the tutorial only by changing parameter values in this file.
# Limit the simulation to 25s
sim-time-limit = 25s
# Let's configure ARP
# ARP in the real world is used to figure out the MAC address of a node from its IPv4 address.
# We do not want to use it in this wireless tutorial as it just adds some uninteresting
# message exchanges before the real communication between the nodes can start. We will use
# the GlobalARP module instead that can automatically provide all the MAC-IP assocoations
# for the nodes out of band.
**.arpType = "GlobalARP"
# Now we are ready to jump into the tutorial
[Config Wireless01]
description = Two nodes communicating via UDP
network = WirelessA
# Configure an application for hostA that sends a constant
# UDP traffic around 800Kbps (+ protocol overhead)
*.hostA.numUdpApps = 1
*.hostA.udpApp[0].typename = "UDPBasicApp"
*.hostA.udpApp[0].destAddresses = "hostB"
*.hostA.udpApp[0].destPort = 5000
*.hostA.udpApp[0].messageLength = 1000B
*.hostA.udpApp[0].sendInterval = exponential(10ms)
# Configure an app that receives the USP traffic (and simply drops the data)
*.hostB.numUdpApps = 1
*.hostB.udpApp[0].typename = "UDPSink"
*.hostB.udpApp[0].localPort = 5000
# Configure the hosts to have a single "ideal" wireless NIC. An IdealWirelessNic
# can be configured with a maximum communication range. All packets withing range
# are always received successfully while out of range messages are never received.
# This is useful if we are not interested how the actual messages get to their destination,
# we just want to be sure that they get there once the nodes are in range.
*.host*.wlan[*].typename = "IdealWirelessNic"
# All radios and MACs should run on 1Mbps in our examples
**.bitrate = 1Mbps
# Mandatory physical layer parameters
*.host*.wlan[*].radio.transmitter.maxCommunicationRange = 500m
# Simplify the IdealWirelessNic even further. We do not care even if there are
# transmission collisions. Any number of nodes in range can transmit at the same time
# and the packets will be still successfully delivered.
*.host*.wlan[*].radio.receiver.ignoreInterference = true
# Result: HostA can send data to hostB using almost the whole 1Mbps bandwidth.
Corresponding NED file:
package inet.tutorials.wireless;
import inet.networklayer.configurator.ipv4.IPv4NetworkConfigurator;
import inet.node.inet.INetworkNode;
import inet.physicallayer.contract.packetlevel.IRadioMedium;
// - create a network and specify the size to 500x500
// - drop an IPv4NetworkConfigurator and rename it to "configurator"
// - drop an IdealRadioMedium module and rename to "radioMedium"
// - drop two standardhosts at the 100,100 and 400,400 position and
// rename them to hostA and hostB
network WirelessA
{
#display("bgb=500,500");
#figure[thruputInstrument](type=gauge; pos=370,90; size=120,120; maxValue=2500; tickSize=500; colorStrip=green 0.75 yellow 0.9 red;label=Number of packets received; moduleName=hostB.udpApp[0]; signalName=rcvdPk);
string hostType = default("WirelessHost");
string mediumType = default("IdealRadioMedium");
submodules:
configurator: IPv4NetworkConfigurator {
#display("p=149,29");
}
radioMedium: <mediumType> like IRadioMedium {
#display("p=309,24");
}
hostA: <hostType> like INetworkNode {
#display("p=50,250");
}
hostB: <hostType> like INetworkNode {
#display("p=450,250");
}
}
I'm using the following project for enabling APNS in my project:
https://github.com/stephenmuss/django-ios-notifications
I'm able to send and receive push notifications on my production app fine, but the sandbox apns is having strange issues which i'm not able to solve. It's constantly not connecting to the push service. When I do manually the _connect() on the APNService or FeedbackService classes, I get the following error:
File "/Users/MyUser/git/prod/django/ios_notifications/models.py", line 56, in _connect
self.connection.do_handshake()
Error: [('SSL routines', 'SSL3_READ_BYTES', 'sslv3 alert handshake failure')]
I tried recreating the APN certificate a number of times and constantly get the same error. Is there anything else i'm missing?
I'm using the endpoints gateway.push.apple.com and gateway.sandbox.push.apple.com for connecting to the service. Is there anything else I should look into for this? I have read the following:
Apns php error "Failed to connect to APNS: 110 Connection timed out."
Converting PKCS#12 certificate into PEM using OpenSSL
Error Using PHP for iPhone APNS
Turns out Apple changed ssl context from SSL3 to TLSv1 in development. They will do this in Production eventually (not sure when). The following link shows my pull request which was accepted into the above project:
https://github.com/stephenmuss/django-ios-notifications/commit/879d589c032b935ab2921b099fd3286440bc174e
Basically, use OpenSSL.SSL.TLSv1_METHOD if you're using python or something similar in other languages.
Although OpenSSL.SSL.SSLv3_METHOD works in production, it may not work in the near future. OpenSSL.SSL.TLSv1_METHOD works in production and development.
UPDATE
Apple will remove SSL 3.0 support in production on October 29th, 2014 due to the poodle flaw.
https://developer.apple.com/news/?id=10222014a
I have worked on APN using python-django, for this you need three things URL, PORT and Certificate provided by Apple for authentication.
views.py
import socket, ssl, json, struct
theCertfile = '/tmp/abc.cert' ## absolute path where certificate file is placed.
ios_url = 'gateway.push.apple.com'
ios_port = 2195
deviceToken = '3234t54tgwg34g' ## ios device token to which you want to send notification
def ios_push(msg, theCertfile, ios_url, ios_port, deviceToken):
thePayLoad = {
'aps': {
'alert':msg,
'sound':'default',
'badge':0,
},
}
theHost = ( ios_url, ios_port )
data = json.dumps( thePayLoad )
deviceToken = deviceToken.replace(' ','')
byteToken = deviceToken.decode('hex') # Python 2
theFormat = '!BH32sH%ds' % len(data)
theNotification = struct.pack( theFormat, 0, 32, byteToken, len(data), data )
# Create our connection using the certfile saved locally
ssl_sock = ssl.wrap_socket( socket.socket( socket.AF_INET, socket.SOCK_STREAM ), certfile = theCertfile )
ssl_sock.connect( theHost )
# Write out our data
ssl_sock.write( theNotification )
# Close the connection -- apple would prefer that we keep
# a connection open and push data as needed.
ssl_sock.close()
Hopefully this would work for you.
i've installed Lighthttpd for windows and i'd created a simple program in c++ which uses fastcgi libraries. i'll post the code here...
#include "fcgi_stdio.h"
#include <stdlib.h>
int count;
void initialize(void)
{
count=0;
}
void main(void)
{
initialize();
while (FCGI_Accept() >= 0) {
printf("Content-type: text/html\r\n"
"\r\n"
"<title>FastCGI Hello! (C, fcgi_stdio library)</title>"
"<h1>FastCGI Hello! (C, fcgi_stdio library)</h1>"
"Request number %d running on host <i>%s</i>\n",
++count, getenv("SERVER_HOSTNAME"));
}
}
I've spawned the fastcgi application in lighthttpd using the below configuration in lightttpd-inc.conf
fastcgi.server = ( ".exe" =>
( "" =>
(
"bin-path" => "D:\tinycgi.exe",
"port" => 8080,
"min-procs" => 1,
"max-procs" => 1
)
)
)
while sending a request using the browser the server is responding with this message in the console
2009-02-18 16:08:34: (mod_fastcgi.c.2494) unexpected end-of-file (perhaps the fa
stcgi process died): pid: 0 socket: tcp:localhost:8080
2009-02-18 16:08:34: (mod_fastcgi.c.3325) response not received, request sent: 1
024 on socket: tcp:localhost:8080 for /new/tinycgi.exe , closing connection
I think the fastcgi application is not spawned correctly.
Thank you,
Varun
First of all, main should return an int (not void).
The problem is most likely that you didn't call FCGX_Init() and didn't initialize the request (with FCGX_InitRequest()) either.
If you want to check if the application is spawned correctly, you should write to a log file, if lighttpd doesn't start the application, the log file won't be created.