Device not accepting incoming connection in J2Me Bluetooth? - java-me

I am trying to do communication between a mobile application (using J2ME and JSR82) and Desktop application (in C# using InTheHand Library).
I am using RFComm protocol with UUID: 00000003-0000-1000-8000-00805f9b34fb.
I have manually specified uuid on both devices. I have mobile application to wait for incoming connections, while desktop application sends data to it.
But, my mobile application just does not listen to incoming connection. It just hangs at the message: "Waiting for incoming connection..."
J2ME code in Mobile Application:
public void startApp() {
if (midletPaused) {
resumeMIDlet();
} else {
initialize();
startMIDlet();
form.append("UID: "+ uuid.toString() +"\n");
//set the device discoverable
try {
LocalDevice localDevice = LocalDevice.getLocalDevice();
localDevice.setDiscoverable(DiscoveryAgent.GIAC);
form.append("Device Address: "+localDevice.getBluetoothAddress()+"\n");
form.append("Name: "+ localDevice.getFriendlyName()+"\n");
}
catch (BluetoothStateException exception) {
form.append(exception.toString()+"\n");
}
//setup a server socket
StreamConnectionNotifier streamConnectionNotifier = null;
try {
String url = "btspp://localhost:000300001000800000805f9b34fb;name=rfcommtest;authorize=true";
//form.append(url);
streamConnectionNotifier = (StreamConnectionNotifier)Connector.open(url);
if (streamConnectionNotifier == null) {
form.append("Error: streamConnectionNotifier is null\n");
return;
}
}
catch (Exception exception) {
form.append(exception.toString()+"\n");
}
//wait for an incoming connection
StreamConnection streamConnection = null;
try {
form.append("Waiting for incoming connection...\n");
streamConnection = streamConnectionNotifier.acceptAndOpen();
if (streamConnection == null) {
form.append("Error: streamConnection is null\n");
} else {
form.append("Connection received.\n");
}
}
catch (Exception exception) {
form.append(exception.toString()+"\n");
}
//write hello and then exit
try {
OutputStream out = streamConnection.openOutputStream();
form.append("Stream \n");
String s = "hello";
out.write(s.getBytes());
out.flush();
streamConnection.close();
form.append("Text Written to stream\n");
}
catch (Exception exception) {
form.append(exception.toString()+"\n");
}
}
midletPaused = false;
}
C# Code in Desktop App:
cli = new BluetoothClient();
BluetoothEndPoint ep1 = new BluetoothEndPoint(info[listBox1.SelectedIndex].DeviceAddress, BluetoothService.RFCommProtocol);
cli.Connect(ep1);
Stream stream = cli.GetStream();
StreamWriter sw = new StreamWriter(stream);
sw.WriteLine("Tesing");
sw.WriteLine("testing");
sw.Flush();
sw.Close();
stream.Close();
Please help me out on this.

Related

How can I send EOF signal to server ,when I use spring integration as tcp client?

I want use spring integration to replace socket client.My socket client code is like this:
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 7779);
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
String str = "hello server!";
pw.write(str);
pw.flush();
socket.shutdownOutput();
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String info = br.readLine();
while (info != null) {
System.out.println("i am client. server says that " + info);
info = br.readLine();
pw.close();
}
br.close();
is.close();
pw.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
socket client will get server's reply msg.
and I use spring integration to do the same job.
spring integration's xml code is like this:
<int:gateway id="gw"
service-interface="org.springframework.integration.samples.tcpclientserver.SimpleGateway"
default-request-channel="input"/>
<int-ip:tcp-connection-factory id="client"
type="client"
host="localhost"
port="7779"
single-use="true"
so-timeout="10000"/>
<int:channel id="input"/>
<int-ip:tcp-outbound-gateway id="outGateway"
request-channel="input"
reply-channel="clientBytes2StringChannel"
connection-factory="client"
request-timeout="10000"
reply-timeout="10000"/>
<int:object-to-string-transformer id="clientBytes2String"
input-channel="clientBytes2StringChannel"/>
it's a part of spring integration's tcp-client-server example https://github.com/spring-projects/spring-integration-samples/tree/master/basic/tcp-client-server
java code is like this:
final Scanner scanner = new Scanner(System.in);
final GenericXmlApplicationContext context = Main.setupContext();
final SimpleGateway gateway = context.getBean(SimpleGateway.class);
final AbstractServerConnectionFactory crLfServer = context.getBean(AbstractServerConnectionFactory.class);
TestingUtilities.waitListening(crLfServer, 10000L);
while (true) {
final String input = scanner.nextLine();
if ("q".equals(input.trim())) {
break;
}
else {
final String result = gateway.send(input);
System.out.println(result);
}
}
System.out.println("Exiting application...bye.");
System.exit(0);
}
public static GenericXmlApplicationContext setupContext() {
final GenericXmlApplicationContext context = new GenericXmlApplicationContext();
if (System.getProperty(AVAILABLE_SERVER_SOCKET) == null) {
System.out.print("Detect open server socket...");
int availableServerSocket = SocketUtils.findAvailableTcpPort(5678);
final Map<String, Object> sockets = new HashMap<>();
sockets.put(AVAILABLE_SERVER_SOCKET, availableServerSocket);
final MapPropertySource propertySource = new MapPropertySource("sockets", sockets);
context.getEnvironment().getPropertySources().addLast(propertySource);
}
System.out.println("using port " + context.getEnvironment().getProperty(AVAILABLE_SERVER_SOCKET));
context.load("classpath:META-INF/spring/integration/tcpClientServerDemo-context.xml");
context.registerShutdownHook();
context.refresh();
return context;
}
and I can't get sever reply, because server doesn't get a eof signal and it still blocked in readLine();
the exception I get :
org.springframework.integration.MessageTimeoutException: Timed out waiting for response.
Here is server code:
try {
ServerSocket serverSocket = new ServerSocket(7779);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String info = br.readLine();
System.out.println("from client : "+info);
while (info != null) {
System.out.println("i am server. message from client is " + info);
info = br.readLine(); //server blocked here
}
socket.shutdownInput();
OutputStream os = socket.getOutputStream();
String replyMsg="welcom from server 7779 ACK\r\n";
os.write(replyMsg.getBytes());
os.close();
br.close();
isr.close();
is.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
so how can I send a eof singal to server so my application will get the server's reply?
Spring Integration currently doesn't support those shutDown*() methods.
Please open a GitHub Issue and we'll take a look.

ReceiveAsync from UDP socket

I want to create a UDP socket to receive data from Local Endpoint.
I do not know the Remote Port where data come from, that's why I thought I would use ReceiveAsync. But it does not work.
I give my code right now and any advice would be useful:
public class Program
{
ManualResetEvent clientDone;
Socket socket;
public static void Main(string[] args)
{
clientDone = new ManualResetEvent(false);
socket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint localIPEP = new IPEndPoint( IPAddress.Any, 0);
socket.Bind( (EndPoint) localIPEP);
while (listening)
Receive();
}
string Receive()
{
string response;
byte[] recvData = new byte[24];
if (socket != null)
{
SocketAsyncEventArgs ae = new SocketAsyncEventArgs();
ae.SetBuffer(recvData, 0, recvData.Length);
// callback
ae.Completed += new EventHandler<SocketAsyncEventArgs>(delegate (object s, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
response.Trim('\0');
}
else
{
response = e.SocketError.ToString();
}
switch (e.LastOperation)
{
case SocketAsyncOperation.Receive:
ProcessReceivedData(e);
break;
}
clientDone.Set();
});
clientDone.Reset();
Console.WriteLine("Local EndPoint: " + ((IPEndPoint)socket.LocalEndPoint).ToString());
socket.ReceiveAsync(ae);
clientDone.WaitOne(1000);
}
return response;
}
}
P.S. I work on Linux .Net Core

bluetooth communication server client stuck j2me

How can I use the same Stream to read/write from server to client or from client to server more than once?
I am making a turn based game over bluetooth. Any ideas on how to achieve this in j2me?
I am using RfCOM protocol.
The client code is
public void serviceSearchCompleted(int transID, int respCode) {
try {
StreamConnection SC = (StreamConnection) Connector.open(connectionURL);
input = SC.openDataInputStream();
output = SC.openDataOutputStream();
} catch (IOException ex) {
ex.printStackTrace();
}
while (true) {
f.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
if (c.getLabel().toString().equalsIgnoreCase("send")) {
try {
output.writeUTF("Hey server");
output.flush();
String msg = input.readUTF();
System.out.println(msg);
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("am here now " + ex);
}
}
}
});
synchronized (lock) {
lock.notify();
}
}
}
Server code:
while (true) {
StreamConnection sc = scn.acceptAndOpen();
RemoteDevice rd = RemoteDevice.getRemoteDevice(sc);
DataInputStream input = sc.openDataInputStream();
DataOutputStream output = sc.openDataOutputStream();
String inMsg = input.readUTF();
System.out.println(inMsg + " recived at " + new Date().toString());
output.writeUTF("Hey client Sent at " + new Date().toString());
output.flush();
}
The stream works only once, then nothing happens when I click send again
Processing CONN_INIT 4
Processing CONN_OPEN 4
Processing CONN_SEND 4
Processing CONN_RECEIVE 4
Hey client Sent at Sun Jul 22 19:47:15 GMT+02:00 2012
Processing CONN_SEND 4
Processing CONN_RECEIVE 4
L2CAPConnectionNotifier.acceptAndOpen will block the loop and wait a new connection.
Move your code from the while body to a new thread.
while (true) {
StreamConnection sc = scn.acceptAndOpen();
final RemoteDevice rd = RemoteDevice.getRemoteDevice(sc);
new Thread() {
public void run() {
treatConnection(rd);
}
}.start();
}
private void treatConnection(RemoteDevice rd) {
DataInputStream input = sc.openDataInputStream();
DataOutputStream output = sc.openDataOutputStream();
String inMsg = input.readUTF();
while (inMsg != null) { // not sure about this stop condition...
System.out.println(inMsg + " recived at " + new Date().toString());
output.writeUTF("Hey client Sent at " + new Date().toString());
output.flush();
inMsg = input.readUTF();
}
}

How do I send a message to a bluetooth device?

Using the bluetooth API in j2me, I want to send a message to another mobile phone. I have been able to discover devices and services on the corresponding devices. I have also been able to connect to the services however when I try to send a message from the server to the client. The message is written but the client does not seem to receive it ..
public void startServer() throws IOException {
UUID uuid = new UUID("1101", false);
//Create the service url
String connectionString = "btspp://localhost:" + uuid + ";name=xyz";
//open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier) Connector.open(connectionString);
//Wait for client connection
System.out.println("\nServer Started. Waiting for clients to connect...");
StreamConnection connection = streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println("Remote device address: " + dev.getBluetoothAddress());
System.out.println("Remote device name: " + dev.getFriendlyName(true));
Survey.setTitle(dev.getFriendlyName(true));
//read string from spp client
try {
DataInputStream in = connection.openDataInputStream();
OutputStream writer=connection.openDataOutputStream();
String str="";
TextField textfield;
for (int i=0;i<questions.size();i++){
textfield = (TextField) questions.elementAt(i);
str += formatSurvey(textfield,i)+"&";
}
writer.write(str.getBytes(), 0, str.getBytes().length);
writer.flush();
System.out.println("Written to client "+str);
System.out.println("Reading "+in.readUTF());
try {
displaySurveyresults(str);
}
catch(Exception e){
System.out.println(e.getMessage());
}
streamConnNotifier.close();
}
catch(Exception e){
System.err.println(e.getMessage());
}
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
switchDisplayable(null , getList1());
list1.append(servRecord.toString(), null);
System.out.println("Service discovered..."+servRecord.toString());
for (int i=0;i<servRecord.length;i++){
try {
System.out.println("Test1");
//StreamConnection con = (StreamConnection) Connector.open(servRecord[i].getConnectionURL(0 , false));
String connURL = servRecord[0].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
// Open connection
StreamConnection con = (StreamConnection) Connector.open(connURL);
System.out.println("Test2");
DataInputStream in = con.openDataInputStream();
System.out.println("Test3"+in.readUTF());
//con.openDataOutputStream().write(142);
System.out.println("Test4 "+in.available());
byte[] bte=new byte[in.available()];
System.out.println("Test5 "+bte.length);
in.read(bte);
System.out.println("Test6");
for (int l=0;l<bte.length;l++){
System.out.println(bte[i]);
System.out.println("Test7");
stringItem.setText(stringItem.getText()+1 + bte[i]);
}
OutputStream outStream=con.openOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(outStream);
writer.write("Vimal");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
have I erred somewhere bcause these are codes from the Net?
Try replacing new UUID("1101", false); with new UUID(0x1101);.

Problem using J2ME WMA to send/receive SMS

I'm using WMADemo of the JavaME SDK 3.0 and it's working fine in simulator.
When I install the application in a mobile device it doesn't work. I tried both port 0 (default SMS) and 50000 (listener) with no success. No exception was thrown.
This is an example that works for me
try {
String dest = "sms://" + yourRecipientNumberString;
MessageConnection mConn = (MessageConnection) Connector.open(dest);
TextMessage sms = (TextMessage) mConn.newMessage(MessageConnection.TEXT_MESSAGE);
sms.setPayloadText(msgText);
mConn.send(sms);
mConn.close();
sent = true;
} catch (IOException ioe) {
ioe.printStackTrace();
sent = false;
} catch (IllegalArgumentException iae) {
iae.printStackTrace();
sent = false;
} catch (SecurityException se) {
se.printStackTrace();
sent = false;
}

Resources