I am developing a mobile application in net-beans that will send and receive SMS, I'm done with sending text but I don't know how to receive SMS in NetBeans mobile application ?
WMA (Wireless Messaging API) is a wireless messaging api defined in MIDP 2.0. These apis are designed to handle text, binary and multipart messages. To make a connection, the application obtains an object implementing the MessageConnection from the Connector class by providing an URL connection string that identifies the address.
/* Make a connection */
public boolean connectSMSServer()
{
try
{
messageConnection messageConnection =
(MessageConnection)Connector.open("sms://:" + port);
messageConnection.setMessageListener(this);
}
catch (Exception e) {
}
}
/* Send text message */
public void sendTextmessage(String address,String message)
{
try
{
//creates a new TextMessage
TextMessage textMessage = (TextMessage)messageConnection.newMessage(
MessageConnection.TEXT_MESSAGE, address);
textMessage.setPayloadText(message);
messageConnection.send(textMessage);
}
catch (Exception e) {
}
}
/* Recieve text message */
public void receiveTextMessage()
{
try
{
Message message = messageConnection.receive();
if (message instanceof TextMessage)
{
TextMessage textMessage = (TextMessage)message;
}
else
{
//Message can be binary or multipart
}
}
catch (Exception e) {
}
}
/* Notify Incoming Message */
public synchronized void notifyIncomingMessage(MessageConnection conn)
{
//notiy thread of incoming message
synchronized (this)
{
notify();
}
}
/* Close Connection */
public void closeConnection()
{
if (messageConnection != null)
{
try
{
messageConnection.setMessageListener(null);
messageConnection.close();
}
catch (Exception e) {
}
}
}
}
When you are coding for Receiving SMS, you need to listen to one particular port. J2ME Application can not read directly from the inbox.
Related
I am working on to establish a message communication between UWP Application on desktop and the Hololens 1.
According to the implementation of Websockets from Microsoft Documentation Websocket Implementation I could
implement the signalling part to the Nodejs with socket.io Server
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
var PORT = 3000;
var userId = 0;
http.listen(PORT, function () {
console.log('listening on *: ' + PORT);
});
io.on('connection', function(socket){
socket.userId = userId++;
console.log('a user connected, user id: ' + socket.userId);
socket.on('mess', function (msg) {
console.log('message from user#' + socket.userId + ": " + msg);
// Send message with emit"mess" to all client
io.emit('mess', msg);
});
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
Both client (uwp app and the hololens could establish to the Server.
On the computer I could send some data to the server.
The problem I currently have is that the Hololens does not receive a message from the server.
For the communication part I use a wrapper class which provide sending and receiving functions for 2 clients. This wrapper class has been generated to dll inorder to reference in 2 difference projekt (uwp app and unity app for hololens)
// Declare "Using" part here...
namespace SocketWrapperNamespace
{
public delegate void OnReceiveMessengerCallback(string msg);
public delegate void OnDisconnectCallback(bool connect);
public class SocketWrapper
{
public event OnReceiveMessengerCallback OnReceiveMessenger;
public event OnDisconnectCallback onDisconnect;
#if !UNITY_EDITOR
private Uri _uri;
private MessageWebSocket messageWebSocket;
private DataWriter dataWriter;
#endif
// Client can call this function to connect
public void Connect(string uri)
{
#if !UNITY_EDITOR
try
{
Connector(uri);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
#endif
}
private async void Connector(string uri)
{
#if !UNITY_EDITOR
// Code here look pretty much like in the example from microsoft documentation
#endif
}
// Function for client to send message to server
public void SendMessage(string emiter, string message)
{
#if !UNITY_EDITOR
try
{
Emit(emiter, message);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
#endif
}
//Emitter
private async void Emit(string emiter, string message)
{
#if !UNITY_EDITOR
try
{
if (messageWebSocket == null)
{
return;
}
if (dataWriter == null)
{
return;
}
string form = string.Format("42[\"{0}\",\"{1}\"]", emiter, message);
dataWriter.WriteString(form);
await dataWriter.StoreAsync();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
#endif
}
//Disconnect
public void Disconnect()
{
#if !UNITY_EDITOR
// Disconnecting server ...
#endif
}
//Message Arrived Handler
private void WebSocket_MessageArrived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
{
#if !UNITY_EDITOR
try
{
if (OnReceiveMessenger == null)
{
return;
}
using (DataReader dataReader = args.GetDataReader())
{
if (dataReader != null)
{
dataReader.UnicodeEncoding = UnicodeEncoding.Utf8;
string message = dataReader.ReadString(dataReader.UnconsumedBufferLength);
OnReceiveMessenger?.Invoke(message);
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
#endif
}
//Websocket Close Handler
private void WebSocket_Closed(IWebSocket sender, WebSocketClosedEventArgs args)
{
#if !UNITY_EDITOR
// Close work here ...
#endif
}
}
On the Hololens I prepare the connection to server and listen to the received message event.
// hololens client call this method to initialize the connection
public void OnStart()
{
socketWrapper = new SocketWrapper();
uri = String.Concat("ws://",server,":3000/socket.io/?EIO=3&transport=websocket");
#if !UNITY_EDITOR
socketWrapper.Connect(uri);
socketWrapper.OnReceiveMessenger += OnMessageArrived_Handler;
socketWrapper.onDisconnect += OnDisconnect_Handler;
#endif
}
//Message Arrived Handler
private void OnMessageArrived_Handler(string msg)
{
// Here I do not received any message from server
}
What mistake did I make her ? I wonder that even though I can connect to the server from hololens but the subscribe part seem not to work ?
Consider the 2 projects are on different location and the same happen to the dll.
I think that I have to setup the SocketWrapper class as Singleton because hololens part instantiate a new Object therefor the subscribing may not work here
Any better suggestion for solve this problem with other implementation would be helpful.
Thanks
I think the best solution now for using WebSocket in C# and Unity environment is WebSocketSharp library.
It has a great implementation and kept up to date for 6 years till now. Also it has 3 examples of how to use it in different scenarios.
I have tried to establish chat connection between two users using xmpp and OpenFire. But i am not able to send and receive message. I have pasted my code below for reference. Any help will be very helpful.
I established a connection with Smack by
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setUsernameAndPassword("admin", "admin");
config.setServiceName("172.21.4.199");
config.setHost("172.21.4.199");
config.setPort(5222);
config.setDebuggerEnabled(true);
config.setConnectTimeout(50000);
XMPPTCPConnection connection = new XMPPTCPConnection(config.build());
XMPPTCPConnection.setUseStreamManagementResumptiodDefault(true);
XMPPTCPConnection.setUseStreamManagementDefault(true);
try {
connection.setPacketReplyTimeout(50000);
connection.connect();
Log.d(TAG, "SetupDefaults -- Connected");
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "SetupDefaults -- Connection failed exc: "+e);
}
and its gets succesfully connected. And i try to send a chat by using
ChatManager chatManager = ChatManager.getInstanceFor(connection);
Chat chat = chatManager.createChat("user2#server.local", new ChatMessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
System.out.println("processMessage -- Sent message: " + message);
}
});
try {
chat.sendMessage("Hai.. Lets we chat!");
}catch (Exception e){
Log.d(TAG, "sendChat Exc: "+e.toString());
}
But i couldn't find that processMessage gets triggered. Because that S.O.P doesn't gets triggered. But i gets
SMACK: SENT (0): Hai.. Lets we chat!
SMACK: RECV (0): Hai.. Lets we chat!
in my console while sending a chat.
Simillarly i use,
PacketListener packetListener = new PacketListener() {
#Override
public void processPacket(Stanza packet) throws SmackException.NotConnectedException {
Message message = (Message)packet;
String from = message.getFrom();
String body = message.getBody();
System.out.println("Message from: " + from + " " + body);
}
};
connection.addPacketListener(packetListener, filter);
to receive the chat. But processPacket also doesn't gets triggered.
PacketListner it's something much more general to handle stanzas, it's not what you really need. You just need a ChatMessageListner
ChatManager chatManager;
chatManager = ChatManager.getInstanceFor(connection);
chatManager.addChatListener(
**new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean createdLocally)
{
if (!createdLocally)
{
chat.addMessageListener(new IncomingMessageListener());;
}
}
})**;
Basic implementation:
class IncomingMessageListener implements ChatMessageListener {
#Override
public void processMessage(Chat arg0, Message message) {
String from = message.getFrom();
String body = message.getBody();
if (body != null)
{
System.out.println(String.format("============ Received message '%1$s' from %2$s\n============", body, from));
guiUpdate.displayMessage(body); /* custom method */
}
else
{
System.out.println("SYSTEM: ping");
}
}
wireless toolkit code
//j2me code for client mobile
public class TCPConnectSend extends MIDlet implements CommandListener {
Display display;
public TCPConnectSend0 () {
frm = new Form ("TCPConnectSend0");
sendCmd = new Command("Send",Command.SCREEN, 1);
frm.addCommand(sendCmd);
frm.setCommandListener(this);
text = new TextField("text:","",40,TextField.ANY);
frm.append(text);
}
public void startApp() {
if(display==null) {
display = Display.getDisplay (this);
}
display.setCurrent(frm);
try {
conn=(SocketConnection)Connector.open("socket://|ip-address|:80");//socket connection to the server
outs=conn.openOutputStream();
} catch(IOException e) { }
}
public void pauseApp() { }
public void destroyApp(boolean unconditional) { }
public void commandAction(Command c, Displayable s) {
if(c==sendCmd) {
try {
outs.write((text.getString()+"\n").getBytes());
} catch(IOException e) {}
} else { }
}
}
server code
//this receives the socket request from client
class TCPServer
{
public static void main(String argv[]) throws Exception
{
try {
ServerSocket server = new ServerSocket(80);
System.out.println("ip address : "+InetAddress.getLocalHost());
System.out.println("waiting for connection");
Socket s1 = server.accept();
System.out.println("connection established");
BufferedReader br = new BufferedReader(new
InputStreamReader(s1.getInputStream()));
while (true) {
String str1 = br.readLine();
System.out.println("client says :" +str1);
if (str1.equals("quit"))
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
//after running this code i m getting a java security exception in my nokia phone any other port no is no responding in the nokia phone
the problem happened because Nokia was blocking the 80 port no for some of its system application so changing of port no along with public ip address did the trick
You should add the public IP of the server in your client code ex.
(SocketConnection)Connection.open( "socket://105.225.251.58" + ":" + "port" );
Note that to use privileged ports like 80, 443, 8080 and generally anything below 1000, you need a code signing certificate(e.g from Thawte) for a real phone.
Otherwise, still to higher un-privileged ports likes 8000 etc
I've been struggling with XMPP chatting a lot through Smack and Openfire server.
My problem is as follows:
Whenever a user sends a message to another user, the message is received correctly at the other user. But any reply doesn't show up at the sender of the first message.
So User 1 sends to User 2 successfully. User 2 is then unable to send to User 1 any reply.
On the other hand, if I restart and let the users login again, User 2 can send to User 1 but not vice versa.
What I'm trying to say is that only the initiator of the chat can send a message, the receiver cannot reply back.
My code looks like this
package xmpp;
public class XMPPClient{
private static final int packetReplyTimeout = 500; // millis
private XMPPConnection connection;
private ChatManager chatManager;
private MessageListener messageListener;
private ConnectionConfiguration config;
private MyTimer t = MyTimer.getInstance();
private ArrayList<String> threadPool = new ArrayList<String>();
public XMPPClient()
{
SmackConfiguration.setPacketReplyTimeout(packetReplyTimeout);
//define openfire server information
config = new ConnectionConfiguration("localhost",5222);
config.setSASLAuthenticationEnabled(false);
config.setSecurityMode(SecurityMode.disabled);
connection = new XMPPConnection(config);
//connect to server
t.start("Connecting to server...");
try {
connection.connect();
} catch (XMPPException e) {
System.err.println("Failed to connect to server! Connect to VPN!\t"+e.getMessage());
System.exit(0);
}
t.end("Connection took ");
//setup chat mechanism
chatManager = connection.getChatManager();
chatManager.addChatListener(
new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean createdLocally)
{
if (!createdLocally)
chat.addMessageListener(new MyMessageListener());
}
});
}
public boolean login(String userName, String password, String resource) {
t.start("Logging in...");
try {
if (connection!=null && connection.isConnected())
connection.login(userName, password, resource);
//set available presence
setStatus(true);
}
catch (XMPPException e) {
if(e.getMessage().contains("auth")){
System.err.println("Invalid Login Information!\t"+e.getMessage());
}
else{
e.printStackTrace();
}
return false;
}
t.end("Logging in took ");
return true;
}
public void setStatus(boolean available) {
if(available)
connection.sendPacket(new Presence(Presence.Type.available));
else
connection.sendPacket(new Presence(Presence.Type.unavailable));
}
public void sendMessage(String message, String buddyJID) throws XMPPException {
System.out.println(String.format("Sending mesage '%1$s' to user %2$s", message, buddyJID));
boolean chatExists = false;
Chat c = null;
for(String tid : threadPool)
{
if((c = chatManager.getThreadChat(tid)) != null)
{
if(c.getParticipant().equals(buddyJID))
{
if(checkAvailability(buddyJID))
{
chatExists = true;
break;
}
else
{
threadPool.remove(tid);
break;
}
}
}
}
if (chatExists)
{
Chat chat = c;
chat.sendMessage(message);
}
else
{
Chat chat = chatManager.createChat(buddyJID, messageListener);
threadPool.add(chat.getThreadID()); System.out.println(chat.getThreadID());
chat.sendMessage(message);
}
}
public void createEntry(String user, String name) throws Exception {
System.out.println(String.format("Creating entry for buddy '%1$s' with name %2$s", user, name));
Roster roster = connection.getRoster();
roster.createEntry(user, name, null);
}
public boolean checkAvailability(String jid)
{
System.out.print("Checking availability for: "+jid+"=");
System.out.println(connection.getRoster().getPresence(jid).isAvailable());
return connection.getRoster().getPresence(jid).isAvailable();
}
public void disconnect() {
if (connection!=null && connection.isConnected()) {
setStatus(false);
connection.disconnect();
}
}
}
import org.jivesoftware.smack.packet.Message;
public class MyMessageListener implements MessageListener {
#Override
public void processMessage(Chat chat, Message message) {
String from = message.getFrom();
String body = message.getBody();
System.out.println(String.format("Received message '%1$s' from %2$s", body, from));
}
}
I'm not sure what the problem is. Any suggestions? Sample code?
Thanks <3
I am not sure if this will help you but I can get reply with this code:
public void chat(String AddressedUser) throws NotConnectedException {
//Create username whom we want to send a message
String userToSend = AddressedUser + "#" + serverDomain;
ChatManager chatmanager = ChatManager.getInstanceFor(connection);
Chat newChat = chatmanager.createChat(userToSend , new MessageListener() {
#Override
public void processMessage(Chat chat, Message message ) {
// TODO Auto-generated method stub
System.out.println("Received message: " + message);
}
});
try {
newChat.sendMessage("Hey");
}
catch (XMPPException e) {
System.out.println("Error Delivering block");
}
}
I am sending "Hey" then what ever other user writes I will see in my logcat.
You haven't specified what the receiver is, for instance, if it is an existing client (like Spark for instance), or more custom code. This would be helpful, as would knowing what version of Smack you are using.
That particular code has several issues with it.
It keeps creating new Chat objects for every message sent, instead of
simply reusing the same chat.
There is no ChatManagerListener registered to handle new Chat messages that are not tied to an existing chat.
the is code is very complicated and it seems is meant only to send msgs.
Here is a sample code that works perfectly, both sending and receiving:
http://www.javaprogrammingforums.com/java-networking-tutorials/551-how-write-simple-xmpp-jabber-client-using-smack-api.html
I want to send a message to my computer from my phone using TCP..My computer is the server and my phone is the client. I am able to send a message from my phone to my computer but in the output, I get null characters ..
I paste my codes below;;
Client ::
public void startApp() {
try {
// establish a socket connection with remote server
streamConnection =
(StreamConnection) Connector.open(connectString);
// create DataOuputStream on top of the socket connection
outputStream = streamConnection.openOutputStream();
dataOutputStream = new DataOutputStream(outputStream);
// send the HTTP request
dataOutputStream.writeChars("Hello");
dataOutputStream.flush();
// create DataInputStream on top of the socket connection
inputStream = streamConnection.openInputStream();
dataInputStream = new DataInputStream(inputStream);
// retrieve the contents of the requested page from Web server
String test="";
int inputChar;
System.out.println("Entering read...........");
while ( (inputChar = dataInputStream.read()) != -1) {
// test=test+((char)inputShar);
results.append((char) inputChar);
}
System.out.println("Leaving read...........");
// display the page contents on the phone screen
//System.out.println(" Result are "+results.toString());
System.out.println(" ");
resultField = new StringItem(null, results.toString());
System.out.println("Client says "+resultField);
resultScreen.append(resultField);
myDisplay.setCurrent(resultScreen);
} catch (IOException e) {
System.err.println("Exception caught:" + e);
} finally {
// free up I/O streams and close the socket connection
try {
if (dataInputStream != null)
dataInputStream.close();
} catch (Exception ignored) {}
try {
if (dataOutputStream != null)
dataOutputStream.close();
} catch (Exception ignored) {}
try {
if (outputStream != null)
outputStream.close();
} catch (Exception ignored) {}
try {
if (inputStream != null)
inputStream.close();
} catch (Exception ignored) {}
try {
if (streamConnection != null)
streamConnection.close();
} catch (Exception ignored) {}
}
}
My server :
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try{
ServerSocket sck=new ServerSocket(880);
Socket client=sck.accept();
InputStream inp= client.getInputStream();
int i;
OutputStream out=client.getOutputStream();
out.write("Testing ".getBytes());
System.out.println("Server has responded ");
String str="";
while((i=inp.read())!=-1){
str=str+((char) i);
System.out.println("USer says "+ str);
}
}
catch(Exception e){
System.out.println("Error "+e);
}
}
}
My output for the server ;;
Server has responded
USer says null H
User says null H null
User says null H null e
etc etc
I am not supposed to get this null character,why I am getting it??
Another thing, my server is writing to the stream but the client is not able to receive that,why is that?Do I need to use a separate thread for that?
Thanks in adv
I would guess that isn't your real code, and that your real code initialized str to null.