communication between java server and javascript - java

I have multithreaded chatting java server which can handle number of clients (java). They can simultaneous talk with each other. They are connected through network socket. Besides their own conversation words, my purpose is to display the conversation words they do in web browser through web application. I am thinking about JavaScript but couldn't figure out how to implement javascript for web application because I will need object or data to pass to javascript side from server( java) side.
Following is the multithreaded server and this works fine with multiple clients.
public class GoodChatServer {
………
public static void main(String[] args) throws Exception {
System.out.println("The chat server is running.");
ServerSocket listener = new ServerSocket(PORT);
try {
….
}
} finally {
…..
}
}
private static class Handler extends Thread {
……….
this.socket = socket;
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
while (true) {
out.println("SUBMITNAME");
name = in.readLine();
if (name == null) {
..
}
synchronized (names) {
if (!names.contains(name)) {
names.add(name);
break;
}

There are a plethora of ways to display chat information from a Java server in a browser using JavaScript. Since you are already using sockets for your Java clients, one option would be to use WebSockets. Oracle provides an introduction to Java Websockets here, which should help you with the server side of things. Mozilla also has a tutorial for writing browser-based websockets here.
Another option you may consider is to relay your data across global real-time network, such as PubNub. PubNub provides a Java API and JavaScript API which will allow you to publish messages from your Java server to your JavaScript clients, using code such as:
<script src="http://cdn.pubnub.com/pubnub.min.js"></script>
<script>(function(){
var pubnub = PUBNUB.init({
publish_key : 'demo',
subscribe_key : 'demo'
})
pubnub.subscribe({
channel : "my_chat_channel",
message : function(m){ alert(m) }, //Display the chat message
})});</script>
On the Java server, you'd write your publish code:
Pubnub pubnub = new Pubnub("demo", "demo");
Callback callback = new Callback() {
public void successCallback(String channel, Object response) {
System.out.println(response.toString());
}
public void errorCallback(String channel, PubnubError error) {
System.out.println(error.toString());
}
};
pubnub.publish("my_chat_channel", "Here is my amazing chat message!" , callback);
PubNub is currently free for up to 1 million messages per month. Good luck!

Related

After successfully establishing a socket connection, how does the server actively send string messages to the client?

I am building a server. I hope that after the Java server and the C# client are connected, I can send information from the HTML to the Java server, and then the Java server sends this information to the client.But I can't get the socket after the successful establishment in the service layer, so my Java server can only send fixed information to the client.
I tried using Class object = new Class(); object.setObject(socket); to save the socket, but when I call this object in the service layer, I get null;
I tried to save the socket using (Map) socket.put("socket", socket), but when I call this method in the service layer, I get null.
This is the code to make the socket. from SocketThread.java
public void run() {
ServerSocket serverSocket = null;
try{
serverSocket = new ServerSocket(5656);
LOGGER.info("socket server start, monitor 5656 port ! ");
Socket socket = serverSocket.accept();
new SocketClientRequest(socket).start();
LOGGER.info("send success ! ");
}catch (Exception ex){
LOGGER.error("send fail ! ");
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
LOGGER.error("服务器延时重启失败 ! ");
}
}
This is a method of reading the information sent by the client using the socket and sending the information to the client. from SocketClientRequest.java
public void run() {
try {
//获取socket中的数据
bufferedInputStream = new
BufferedInputStream(socket.getInputStream());
byte[] clientCharStream = new byte[messageLengthBytes];
bufferedInputStream.read(clientCharStream);
System.out.println(new String(clientCharStream, "utf-8"));
OutputStream out = socket.getOutputStream();
out.write(new String("welcome_send_server!").getBytes());
} catch (IOException e) {
LOGGER.error("read massage error [{}]", e);
}
}
Create a connection when the project starts
#EnableScheduling
#SpringBootApplication
public class GzserverApplication {
public static void main(String[] args) {
SpringApplication.run(GzserverApplication.class, args);
SocketServer socketServer = new SocketServer();
socketServer.start();
}
}
Until this step, everything is fine, but the key problem is coming.
I need to send information to the client through my controller.
this is controller
#ResponseBody
#RequestMapping(value = "firstSend)
public SResult<String> firstSend(String uName, String pNum, String time){
try{
return httpService.firstSend(uName, pNum, time);
}catch (Exception ex){
LOGGER.error(ex.getMessage(), ex);
}
return SResult.failure("fail of connect");
}
this is service
public SResult<String> firstSend(String uName, String pNum, String time) throws Exception {
String token = TokenUtil.sign(uName);
System.out.println("token code : "+token);
SocketObject socketObject = new SocketObject();
Map<String, Socket> socketMap = socketObject.socket();
Socket socket1 = socketMap.get("Socket"); // is null
Socket socket2 = socketObject.getSocket(); // is null
return SResult.success(token);
}
I hope that after the connection is successfully created, the socket can be used in the service layer, and the information is sent to the client through the socket, but no matter what I do, the socket is null in the service layer.please give me a help, thank you very much
You should not be dealing with Sockets if using Spring. Spring is a very extensive abstraction layer, that lets you avoid having to deal with the nasty details that Sockets introduce.
In your controller, you call: SocketObject socketObject = new SocketObject(); This creates a new object, presumably with a null-initialized Socket object. Nowhere in this code do you pass a socket object from the main() scope to any other scope (for example using a method named setSocket(Socket socket).
However, and I cannot stress this enough, you should not use Sockets in Spring. Think about what problem you are trying to solve, and ask yourself (why do I need to send information to the client). It is likely that Spring has a module that will do this for you in a much more scalable and manageable way.
For example, perhaps you need to establish 2-way communication between the server and the client, and need to post information to the client periodically. In this case, the WebSocket protocol (and associated Spring Websocket library) might be for you.
This is likely an XY problem. If you edit your question to illustrate the functionality you are trying to implement, it may be easier to help

How can i extract all the information from a web service?

I'm currently working with a little device that works to measure some stuff from electricity like voltage, power consumption and so more... and that device has a web service that i can get it by just writting the IP on my web browser and a panel is shown up... but it is limited i can't extract ALL the information from the device.
So, i created a CLIENT on java to make a connection directly to the server, and this is my code.
I need to mention that the protocol i'm using is Modbus TCP/IP
import de.re.easymodbus.modbusclient.*;
public class run {
public static void main(String[] args)
{
ModbusClient modbusClient = new ModbusClient("127.0.0.1",502);
try
{
modbusClient.Connect();
modbusClient.WriteSingleCoil(0, true);
modbusClient.WriteSingleRegister(0, 1234);
modbusClient.WriteMultipleRegisters(11, ModbusClient.ConvertFloatToTwoRegisters((float) 123.56));
System.out.println(modbusClient.ReadCoils(0, 1)[0]);
System.out.println(modbusClient.ReadHoldingRegisters(0, 1)[0]);
System.out.println(ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(11, 2)));
}
catch (Exception e)
{
}
}
I made a connection, but how can i directly get all the information from the service once i'm connected to the service?
Thanks.

Communication management in client/server application

Let me explain the purpose of my application so you can guide me about the best possible approach.
The idea is building a web application to remotely manage some particular equipments that my company manufactures. These equipments will periodically connect to the remote server to send/receive certain data (through simple socket communication but they don't use Java); this data will be stored in the corresponding data base and will be available through the web application for the different users.
In the same way, when you access through the web interface, each client will be able to see their equipments and perform different changes in the configuration. At this point there are 2 possible options and this is the reason of this post:
The easiest but not the best option: the user performs some changes and I save those changes in the data base. When the equipment later establish communication to the server, then it'll read those changes and update its configuration.
The ideal solution: as soon as the user save the changes through the web interface and push the "send" button, those changes are sent to the corresponding equipment.
As mentioned above, these equipments will periodically open a socket communication (let's say every 5 minutes) to the server to send their configuration. At this moment, in order to implement the "ideal solution", the only option I can think of is not to close that socket so I can use it to immediately send information back to the equipment when a certain user makes any changes.
If this application grows along the time, I'm afraid that too many open sockets/threads can crash my application.
Let me illustrate with some code I was playing around. I know this is far from the final solution, it's just to help you understand what I'm looking for.
First of all, I register the socket server during the start-up of the web server (Tomcat in this case):
package org.listeners;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.sockets.KKMultiServer;
public class ApplicationListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
KKMultiServer kKMultiServer = new KKMultiServer();
Thread serverThread = new Thread(kKMultiServer);
serverThread.start();
event.getServletContext().setAttribute("PlainKKMultiServer", kKMultiServer);
}
public void contextDestroyed(ServletContextEvent event) { }
}
This is the main socket server class that listens for new connections:
public class KKMultiServer implements Runnable {
private Map<Long, KKMultiServerThread_v2> createdThreads = new HashMap<Long, KKMultiServerThread_v2>();
#Override
public void run() {
boolean listening = true;
try (ServerSocket serverSocket = new ServerSocket(5000)) {
while (listening) {
KKMultiServerThread_v2 newServerThread = new KKMultiServerThread_v2(serverSocket.accept(), this);
Thread myThread = new Thread(newServerThread);
myThread.start();
Long threadId = myThread.getId();
System.out.println("THREAD ID: " + threadId);
}
} catch (IOException e) {
System.err.println("Could not listen on port " + 5000);
System.exit(-1);
}
}
public Map<Long, KKMultiServerThread_v2> getCreatedThreads() {
return createdThreads;
}
}
And the thread class created with every single petition from each of the equipments (dispensers) to handle the socket communication:
public class KKMultiServerThread_v2 implements Runnable {
private Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
private long dispenserCode;
private KKMultiServer kKMultiServer;
public KKMultiServerThread_v2(Socket socket, KKMultiServer kKMultiServer) {
this.socket = socket;
this.kKMultiServer = kKMultiServer;
}
public void run() {
try {
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
readDataFromDispenser();
}
private void readDataFromDispenser() {
String inputLine;
try {
while ((inputLine = in.readLine()) != null) {
if (inputLine.equals("Bye")) {
break;
}
if (dispenserCode == 0) {
dispenserCode = 1111; // this code will be unique per equipment
this.kKMultiServer.getCreatedThreads().put(dispenserCode, this);
}
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendDataToDispenser(String dataToSend) {
if (!socket.isClosed() && socket.isConnected()) {
out.println(dataToSend);
} else {
this.kKMultiServer.getCreatedThreads().remove(this);
}
}
}
Now that the socket is created and alive I can use it directly from the web application to send messages back to the equipment (Struts Action in this case)
public class HelloWorldAction extends ActionSupport {
private static final long serialVersionUID = 1L;
public String sendMessageToDispenser() throws Exception {
ServletContext context = ServletActionContext.getServletContext();
KKMultiServer kKMultiServer = (KKMultiServer) context.getAttribute("PlainKKMultiServer");
Map<Long, KKMultiServerThread_v2> currentThreads = kKMultiServer.getCreatedThreads();
Iterator<Long> it = currentThreads.keySet().iterator();
while (it.hasNext()) {
Long key = (Long) it.next();
KKMultiServerThread_v2 currentThread = currentThreads.get(key);
currentThread.sendDataToDispenser("DATA TO YOU!");
}
return SUCCESS;
}
}
Do you think it's possible to perform this solution? I mean, keeping these connections open so I can access my equipments whenever necessary (without waiting for the periodically connections). What's the best approach? If you have any other suggestions please let me know.
Thank you very much.
To my mind it clearly depends on how many equipment will be connected to your system. Sockets are not always sending data so it can have low effect on the overall performance. Though, Socket are know to be a little slow, if you have a lot of data to send to/from your equipments, you should consider this.
If you want to have send data from your server to your client you have few solutions
Your server knows all your equipment after registering for example. When starting you equipment connect to the server. (be careful about local network redirection)
Your equipment and server use sockets to communicate
I don't think there is another solution but I can be wrong. If your equipment request your server every X seconds, it will never be exactly perfeclty on time.

Android Wi-Fi Direct Network

I am developing an application on Android where I am searching for all the peers in the range and afterwards connect with all of them, The device who initiated the the discovery become the group owner and all others become client, I have done all the connection thing but now I want to the group owner to send the message to all the connecting peers, How to achieve this and also please tell me what is the methodology in peer-to-peer communication , Does p2p in Android also use IP to send and receive data?
Thankyou
Regards Talib.
Wi-Fi Direct/P2P can be considered as normal Wi-Fi but where the group owner (GO) acts as a software access point (dhcp server, provisioning, etc). So to answer your last question, yes Wi-Fi Direct also uses IP to send and receive data.
You want to send data to all members in the group? There are two solutions for this:
Broadcast the message once using multicast.
Send the message to each individuel client in the group.
The most efficient method would be solution 1, to broadcast the data using multicast, as you would only need to send the data once. Unfortunately Wi-Fi multicast support is very fragmented in Android, as a lot of devices seem to block non-unicast traffic. See this article for more in depth information if you want to go down this route.
Solution 2 is the best method if you want to guarantee support on all devices and only transmit a small amount of data. The GO need the IP addresses of the clients in the group, but because of the way Wi-Fi Direct is implemented in Android, only the GO IP is known to all devices. One solution is to let the clients connect to a socket on the GO, to get their IP address:
Client code
private static final int SERVER_PORT = 1030;
... // on group join:
wifiP2pManager.requestConnectionInfo(channel, new ConnectionInfoListener() {
#Override
public void onConnectionInfoAvailable(WifiP2pInfo p2pInfo) {
if (!p2pInfo.isGroupOwner) {
// Joined group as client - connect to GO
Socket socket = new Socket();
socket.connect(new InetSocketAddress(p2pInfo.groupOwnerAddress, SERVER_PORT));
}
}
});
Group owner code:
private static final int SERVER_PORT = 1030;
private ArrayList<InetAddress> clients = new ArrayList<InetAddress>();
public void startServer() {
clients.clear();
ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
// Collect client ip's
while(true) {
Socket clientSocket = serverSocket.accept();
clients.add(clientSocket.getInetAddress());
clientSocket.close();
}
}
Now all you need to do is start a serversocket on each client, and make to GO iterate through the client list creating a socket connection to each and sending the message you want to broadcast.
Now we have https://github.com/libp2p/go-libp2p-pubsub - for handling multicast messages (and it's also could shard network into topics)
and we also have some pretty peer discovery protocol like that: https://github.com/libp2p/go-libp2p-examples/blob/master/chat-with-mdns/mdns.go
So, you can very easily to interact with topic messages multicast in local network, just using libp2p
I've just test https://github.com/MoonSHRD/p2chat-android which wrap solution you need into single library, which can be used from android.
This far we could interact with high level of messages instead of interaction with sockets or streams at low levels. Hope this will help someone.
p.s. However, I should notice, that I didn't test mDNS discovery in wi-fi direct networks yet
There are several options to start with but you can choose according to your requirements. It's fairly easy to broadcast and discover the service using jmdns/jmdns. Here is the example from docs,
Service Registration
import java.io.IOException;
import java.net.InetAddress;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceInfo;
public class ExampleServiceRegistration {
public static void main(String[] args) throws InterruptedException {
try {
// Create a JmDNS instance
JmDNS jmdns = JmDNS.create(InetAddress.getLocalHost());
// Register a service
ServiceInfo serviceInfo = ServiceInfo.create("_http._tcp.local.", "example", 1234, "path=index.html");
jmdns.registerService(serviceInfo);
// Wait a bit
Thread.sleep(25000);
// Unregister all services
jmdns.unregisterAllServices();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Service Discovery
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceListener;
public class ExampleServiceDiscovery {
private static class SampleListener implements ServiceListener {
#Override
public void serviceAdded(ServiceEvent event) {
System.out.println("Service added: " + event.getInfo());
}
#Override
public void serviceRemoved(ServiceEvent event) {
System.out.println("Service removed: " + event.getInfo());
}
#Override
public void serviceResolved(ServiceEvent event) {
System.out.println("Service resolved: " + event.getInfo());
}
}
public static void main(String[] args) throws InterruptedException {
try {
// Create a JmDNS instance
JmDNS jmdns = JmDNS.create(InetAddress.getLocalHost());
// Add a service listener
jmdns.addServiceListener("_http._tcp.local.", new SampleListener());
// Wait a bit
Thread.sleep(30000);
} catch (UnknownHostException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
if you are developing desktop application in java, your goal should be to find the best cross-platform DNS-SD (Zeroconf, Bonjour, DNS self discovery) library exists out there.
There are other pure Java DNS-SD implementations, but it's unclear if any of them offer a library that is as easy to use or fully tested as DNS-SD. Head over to the
Waiter once. However, I prefer going through the jmdns, It works well. As the peer to peer connection is supposed to use IP(it have to), you can send/receive data easily once the connection is established.

How to send SMS in Java

What are the possible ways to send and receive sms from Java application?
How?
(Disclaimer: I work at Twilio)
Twilio offers a Java SDK for sending SMS via the Twilio REST API.
if all you want is simple notifications, many carriers support SMS via email; see SMS through E-Mail
There is an API called SMSLib, it's really awesome.
http://smslib.org/
Now you have a lot of Saas providers that can give you this service using their APIs
Ex: mailchimp, esendex, Twilio, ...
The best SMS API I've seen in Java is JSMPP. It is powerful, easy to use, and I used it myself for an enterprise-level application (sending over 20K SMS messages daily).
This API created to reduce the verbosity of the existing SMPP API.
It's very simple and easy to use because it hides the complexity of
the low level protocol communication such as automatically enquire
link request-response.
https://code.google.com/p/jsmpp/
I've tried some other APIs such as Ozeki, but most of them either is commercial or has limitation in its throughput (i.e can't send more than 3 SMS messages in a second, for example).
You Can Do this With A GSM Modem and Java Communications Api [Tried And Tested]
First You Need TO Set Java Comm Api
This Article Describes In Detail How to Set Up Communication Api
Next You Need A GSM Modem (preferably sim900 Module )
Java JDK latest version preferable
AT Command Guide
Code
package sample;
import java.io.*;
import java.util.*;
import gnu.io.*;
import java.io.*;
import org.apache.log4j.chainsaw.Main;
import sun.audio.*;
public class GSMConnect implements SerialPortEventListener,
CommPortOwnershipListener {
private static String comPort = "COM6"; // This COM Port must be connect with GSM Modem or your mobile phone
private String messageString = "";
private CommPortIdentifier portId = null;
private Enumeration portList;
private InputStream inputStream = null;
private OutputStream outputStream = null;
private SerialPort serialPort;
String readBufferTrial = "";
/** Creates a new instance of GSMConnect */
public GSMConnect(String comm) {
this.comPort = comm;
}
public boolean init() {
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(comPort)) {
System.out.println("Got PortName");
return true;
}
}
}
return false;
}
public void checkStatus() {
send("AT+CREG?\r\n");
}
public void send(String cmd) {
try {
outputStream.write(cmd.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(String phoneNumber, String message) {
char quotes ='"';
send("AT+CMGS="+quotes + phoneNumber +quotes+ "\r\n");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// send("AT+CMGS=\""+ phoneNumber +"\"\r\n");
send(message + '\032');
System.out.println("Message Sent");
}
public void hangup() {
send("ATH\r\n");
}
public void connect() throws NullPointerException {
if (portId != null) {
try {
portId.addPortOwnershipListener(this);
serialPort = (SerialPort) portId.open("MobileGateWay", 2000);
serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
} catch (PortInUseException | UnsupportedCommOperationException e) {
e.printStackTrace();
}
try {
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
/** These are the events we want to know about*/
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
serialPort.notifyOnRingIndicator(true);
} catch (TooManyListenersException e) {
e.printStackTrace();
}
//Register to home network of sim card
send("ATZ\r\n");
} else {
throw new NullPointerException("COM Port not found!!");
}
}
public void serialEvent(SerialPortEvent serialPortEvent) {
switch (serialPortEvent.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[2048];
try {
while (inputStream.available() > 0)
{
int numBytes = inputStream.read(readBuffer);
System.out.print(numBytes);
if((readBuffer.toString()).contains("RING")){
System.out.println("Enter Inside if RING Loop");
}
}
System.out.print(new String(readBuffer));
} catch (IOException e) {
}
break;
}
}
public void outCommand(){
System.out.print(readBufferTrial);
}
public void ownershipChange(int type) {
switch (type) {
case CommPortOwnershipListener.PORT_UNOWNED:
System.out.println(portId.getName() + ": PORT_UNOWNED");
break;
case CommPortOwnershipListener.PORT_OWNED:
System.out.println(portId.getName() + ": PORT_OWNED");
break;
case CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED:
System.out.println(portId.getName() + ": PORT_INUSED");
break;
}
}
public void closePort(){
serialPort.close();
}
public static void main(String args[]) {
GSMConnect gsm = new GSMConnect(comPort);
if (gsm.init()) {
try {
System.out.println("Initialization Success");
gsm.connect();
Thread.sleep(5000);
gsm.checkStatus();
Thread.sleep(5000);
gsm.sendMessage("+91XXXXXXXX", "Trial Success");
Thread.sleep(1000);
gsm.hangup();
Thread.sleep(1000);
gsm.closePort();
gsm.outCommand();
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Can't init this card");
}
}
}
You can use Nexmo to send SMS as well as receive SMS.
Sending SMS with the Nexmo Java Library is fairly straightforward. After creating a new account, renting a virtual number, and getting your API key & secret you can use the library to send SMS like so:
public class SendSMS {
public static void main(String[] args) throws Exception {
AuthMethod auth = new TokenAuthMethod(API_KEY, API_SECRET);
NexmoClient client = new NexmoClient(auth);
TextMessage message = new TextMessage(FROM_NUMBER, TO_NUMBER, "Hello from Nexmo!");
//There may be more than one response if the SMS sent is more than 160 characters.
SmsSubmissionResult[] responses = client.getSmsClient().submitMessage(message);
for (SmsSubmissionResult response : responses) {
System.out.println(response);
}
}
}
To receive SMS you'll need to set up a server that consumes a webhook. That's fairly simple as well. I recommend checking out our tutorial on receiving SMS with Java.
Disclosure: I work for Nexmo
There are two ways :
First : Use a SMS API Gateway which you need to pay for it , maybe you find some trial even free ones but it's scarce .
Second : To use AT command with a modem GSM connected to your laptop .
that's all
TextMarks gives you access to its shared shortcode to send and receive text messages from your app via their API. Messages come from/to 41411 (instead of e.g. a random phone# and unlike e-mail gateways you have the full 160 chars to work with).
You can also tell people to text in your keyword(s) to 41411 to invoke various functionality in your app. There is a JAVA API client along with several other popular languages and very comprehensive documentation and technical support.
The 14 day free trial can be easily extended for developers who are still testing it out and building their apps.
Check it out here: TextMarks API Info
OMK.smpp. API. it's base on SMPP
and simulator is also available for free
LOGICA SMPP API.
And another option is Kannel a free WAP and SMS gateway.
I suggest a cloud based solution like Twilio. Cloud based solutions are cost-effective, than an in-house solution as the there is no ongoing maintenance, required. SMS through email is not an elegant solution, as you have to get the carrier information from the user and you can never be sure that you can text all mobile numbers.
I am using twilio java api in my web application, to send sms from serverside. within few minutes, you can integrate with your app.
https://www.twilio.com/docs/java/install
Here's an example sending an SMS message from the docs:
import com.twilio.sdk.TwilioRestClient;
import com.twilio.sdk.TwilioRestException;
import com.twilio.sdk.resource.factory.MessageFactory;
import com.twilio.sdk.resource.instance.Message;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
import java.util.List;
public class Example {
// Find your Account Sid and Token at twilio.com/user/account
public static final String ACCOUNT_SID = "{{ account_sid }}";
public static final String AUTH_TOKEN = "{{ auth_token }}";
public static void main(String[] args) throws TwilioRestException {
TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
// Build a filter for the MessageList
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Body", "Test Twilio message"));
params.add(new BasicNameValuePair("To", "+14159352345"));
params.add(new BasicNameValuePair("From", "+14158141829"));
MessageFactory messageFactory = client.getAccount().getMessageFactory();
Message message = messageFactory.create(params);
System.out.println(message.getSid());
}
}
You can you LOGICA SMPP Java API for sending and Recieving SMS in Java application.
LOGICA SMPP is well proven api in telecom application. Logica API also provide you with signalling capicity on TCP/IP connection.
You can directly integrate with various telecom operator accross the world.
It depends on how you're going to work and who your provider is.
If you work with a sms-gateway company you'll probably work through SMPP protocol (3.4 is still the most common), then have a look on OpenSMPP and jSMPP. These are powerful libs to work with SMPP.
If you're going to work with your own hardware (f.e. a gsm-modem) the easiest way to send messages is through AT commands, they differ depends on the model, so, you should find out what AT commands is supported by your modem. Next, if your modem has an IP and open to connection, you can send commands through java socket
Socket smppSocket = new Socket("YOUR_MODEM_IP", YOUR_MODEM_PORT);
DataOutputStream os = new DataOutputStream(smppSocket.getOutputStream());
DataInputStream is = new DataInputStream(smppSocket.getInputStream());
os.write(some_byte_array[]);
is.readLine();
Otherwise you'll work through a COM port, but the method is the same (sending AT commands), you can find more information how to work with serial ports here.
You can use Twilio for this. But if you are looking for some tricky workaround you can follow the workaround I have mentioned below.
This is not possible for receiving sms. But this is a tricky method you can use to send sms to number of clients. You can use twitter API. We can follow twitter account from our mobile phone with a sms. We just have to send sms to twitter. Imagine we create a twitter account with the user name of #username. Then we can send sms to 40404 as shown below.
follow #username
Then we start to get tweets which are tweeted in that account.
So after we create a twitter account then we can use Twitter API to post tweets from that account. Then all the clients who have follow that account as I mentioned before start to receiving tweets.
You can learn how to post tweets with twitter API from following link.
Twitter API
Before you start developing you have to get permission to use twitter api. You can get access to twitter api from following link.
Twitter Developer Console
This is not the best solution for your problem.But hope this help.
We also love Java in Wavecell, but this question can be answered without language-specific details since we have a REST API which will cover most of your needs:
curl -X "POST" https://api.wavecell.com/sms/v1/amazing_hq/single \
-u amazing:1234512345 \
-H "Content-Type: application/json" \
-d $'{ "source": "AmazingDev", "destination": "+6512345678", "text": "Hello, World!" }'
Look at this questions if you have problems with sending HTTP requests in Java:
HTTP POST using JSON in Java
How can I send json object in http post in java
For specific cases you can also consider using the SMPP API and already mentioned JSMPP library will help with that.
There is Ogham library. The code to send SMS is easy to write (it automatically handles character encoding and message splitting). The real SMS is sent either using SMPP protocol (standard SMS protocol) or through a provider.
You can even test your code locally with a SMPP server to check the result of your SMS before paying for real SMS sending.
package fr.sii.ogham.sample.standard.sms;
import java.util.Properties;
import fr.sii.ogham.core.builder.MessagingBuilder;
import fr.sii.ogham.core.exception.MessagingException;
import fr.sii.ogham.core.service.MessagingService;
import fr.sii.ogham.sms.message.Sms;
public class BasicSample {
public static void main(String[] args) throws MessagingException {
// [PREPARATION] Just do it once at startup of your application
// configure properties (could be stored in a properties file or defined
// in System properties)
Properties properties = new Properties();
properties.setProperty("ogham.sms.smpp.host", "<your server host>"); // <1>
properties.setProperty("ogham.sms.smpp.port", "<your server port>"); // <2>
properties.setProperty("ogham.sms.smpp.system-id", "<your server system ID>"); // <3>
properties.setProperty("ogham.sms.smpp.password", "<your server password>"); // <4>
properties.setProperty("ogham.sms.from.default-value", "<phone number to display for the sender>"); // <5>
// Instantiate the messaging service using default behavior and
// provided properties
MessagingService service = MessagingBuilder.standard() // <6>
.environment()
.properties(properties) // <7>
.and()
.build(); // <8>
// [/PREPARATION]
// [SEND A SMS]
// send the sms using fluent API
service.send(new Sms() // <9>
.message().string("sms content")
.to("+33752962193"));
// [/SEND A SMS]
}
}
There are many other features and samples / spring samples.
You can use AT & T commands for sending sms using GSM modem.

Categories