How make a multi client server using Bluetooth API in j2me? - java-me

I am planning to implement a server using Bluetooth API using J2ME. I want multiple clients to be able to connect to it at the same time but I could not find much on the NET.
UUID uuid = new UUID("1101", false);
String SurveyAnswer="";
//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...");
while(true){
StreamConnection connection = streamConnNotifier.acceptAndOpen();
}
How do I modify these codes in order for it to work as a multi client server?

That's a standard problem. When the StreamConnection connection = streamConnNotifier.acceptAndOpen(); returns you have to spawn a Thread which uses the connection. The main Thread then reenters the accept and waits for next connection.
UUID uuid = new UUID("1101", false); String SurveyAnswer="";
//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...");
while(true){
StreamConnection connection = streamConnNotifier.acceptAndOpen();
System.out.println("Client connected starting communication");
new CommunicationThread(connection).start();
}
In the class CommunicationThreads run method you can then get the streams and communicate.

Related

Using Asp.net MVC 5 with RabbitMQ and SignalR

I have an asp.net MVC 5 application. Now I want to have a new feature allow me to receive GPS signal from devices and update devices real time in web client side.
My plan is to use RabbitMQ to handle message queue and SignalR to notify clients for postion update
My code in Rabbit consumer console application like this
var client = GlobalHost.ConnectionManager.GetHubContext<MyHub>().Clients;
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
var queueName = channel.QueueDeclare().QueueName;
channel.ExchangeDeclare("mychannel", "fanout");
channel.QueueBind(queueName, "mychannel", "");
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
Console.WriteLine("[x] Receive {0}", message);
client.All.hello(message);
};
channel.BasicConsume(queue: queueName,
autoAck: true,
consumer: consumer);
Console.WriteLine("Press Enter to quit");
Console.ReadLine();
}
}
But the code is not fired when I produce a message to RabbitMQ. If I remove code of signalR client:
var client = GlobalHost.ConnectionManager.GetHubContext<MyHub>().Clients;
things work as expected and I can receive message as usual
My question is:
Is my approach correct
if the approach correct then how to make it work?
Many thanks

TcpIp communication from an Azure Function?

I have an azure Queue trigger function that has this code:
using (var client = new TcpClient(AddressFamily.InterNetworkV6))
{
client.Client.DualMode = true;
client.Connect(endpoint);
var data = Encoding.ASCII.GetBytes("test");
using (var outStream = client.GetStream())
{
outStream.Write(data, 0, data.Length);
}
}
The error I am getting back:
A connection attempt failed because the connected party did not
properly respond after a period of time, or established connection
failed because connected host has failed to respond
The endpoint address looks correct and this code works when I debug locally, so I suspect that the azure server might not be allowing the outbound connection.
Any ideas why this connection is not working?
Update: This is still not working and I have tried generating the client in the following ways:
// DualMode IPV6
var client = new TcpClient(AddressFamily.InterNetworkV6);
client.Client.DualMode = true;
client.Connect(endpoint);
// SingleMode Internetwork
var client = new TcpClient(AddressFamily.InterNetwork);
client.Connect(endpoint);
// Just Endpoint
var client = new TcpClient(endpoint);
client.Connect(endpoint);
// Normal
var client = new TcpClient(hostAddress, port);
// Forced IPV6
var client = new TcpClient("::ffff:" + hostAddress, port);
Debugging locally, all of these methods except for "forced IPV6" work just fine. On the server, I get these errors:
== DualMode IPV6
Failed PingBack: A connection attempt failed because the connected party did not properly
respond after a period of time, or established connection failed because connected host
has failed to respond [::ffff:204.16.184.62]:3164
== SingleMode Internetwork
Failed PingBack: A connection attempt failed because the connected party did not properly
respond after a period of time, or established connection failed because connected host
has failed to respond 204.16.184.62:3164
== Just Endpoint
Failed PingBack: The requested address is not valid in its context
== Normal
Failed PingBack: A connection attempt failed because the connected party did not properly
respond after a period of time, or established connection failed because connected host
has failed to respond 204.16.184.62:3164
== Forced IPV6
Failed PingBack: The requested address is not valid in its context [::ffff:204.16.184.62]:3164
Looking at your TcpClient instance,
var client = new TcpClient(AddressFamily.InterNetworkV6)
there's no IPv6 in Azure Functions yet. Switch your AddressFamily to v4:
var client = new TcpClient(AddressFamily.InterNetwork)
There are no restrictions on outbound desinations in App Service/Functions.

HTTP :connect timeout and read timeout for URLStreamHandler with SAAJ working for windows but not working on linux sytem

I'm a beginner when it comes to HTTP connections.
Currently i'm working with SAAJ api to have my soap based client, where to handle timeouts i ended up using URLStreamHandler for HTTP connection properties with the endpoints.
Problem is that this timeout works for my windows based system, however it isn't working for the Linux server it is going to go live on.
below is the code for fetching endpoint with set properties. It is a HTTP POST connection.
URL endpoint = new URL (null, url, new URLStreamHandler () {
protected URLConnection openConnection (URL url) throws IOException {
// The url is the parent of this stream handler, so must create clone
URL clone = new URL (url.toString ());
HttpURLConnection connection = (HttpURLConnection) clone.openConnection();
connection.setRequestProperty("Content-Type",
"text/xml");
connection.setRequestProperty("Accept",
"application/soap+xml, text/*");
// If we cast to HttpURLConnection, we can set redirects
// connection.setInstanceFollowRedirects (false);
connection.setDoOutput(true);
connection.setConnectTimeout(3 * 1000);
connection.setReadTimeout(3 * 1000);
return connection;
for the SAAJ API part, below is the implementation, pretty basic one
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory
.newInstance();
soapConnection = soapConnectionFactory.createConnection();
is = new ByteArrayInputStream(command.getBytes());
SOAPMessage request = MessageFactory.newInstance(
SOAPConstants.SOAP_1_1_PROTOCOL).createMessage(
new MimeHeaders(), is);
MimeHeaders headers = request.getMimeHeaders();
headers.addHeader("Content-Type", "text/xml");
request.saveChanges();
ByteArrayOutputStream out = new ByteArrayOutputStream();
request.writeTo(out);
soapResponse = soapConnection.call(request, endpoint);
Is it that system properties would affect connect or read timeout. If so please let me know what could cause this behavior.

Error while writing to an Azure Worker role Input Endpoint

I'm trying to create an azure application which can recieve messages on a TCP port. I have configured an input endpoint shown below :
Endpoint Name:GPRSEndpoint
Type:Input
Protocol:TCP
Port:10000
My azure worker role code looks like this:-
TcpListener listener = new TcpListener(RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["GPRSEndpoint"].IPEndpoint);
listener.ExclusiveAddressUse = false;
listener.Start();
while (true)
{
Thread.Sleep(100);
if (listener.Pending())
{
Trace.WriteLine("Incoming Request", "Information");
TcpClient c = listener.AcceptTcpClient(); //waiting for client to connect
Stream s = c.GetStream();
StreamReader sr = new StreamReader(s);
string text = sr.ReadLine();
if (text != null && text.Length > 0)
{
Trace.WriteLine("Saving GPRS Packets into Storage Table", "Information");
//Saving GPRS Packets into Storage Table
Site site = new Site();
site.GPRSPacket = text;
var insertOperation = TableOperation.Insert(site);
siteTable.Execute(insertOperation);
}
c.Close();
}
Trace.TraceInformation("Working", "Information");
}
}
And finally my client program looks like this:-
TcpClient c = new TcpClient();
Console.WriteLine("\nConnecting to Azure...");
IPAddress AzureWorkeraddress = IPAddress.Parse("168.63.239.54");
//String AzureWorkeraddress = "http://clienttcpcloud.cloudapp.net/";
//IPAddress AzureWorkeraddress = IPAddress.Parse("65.52.184.129");
c.Connect(AzureWorkeraddress, 10000); //Azure Worker Role's INPUT TCP Endpoint 168.63.239.54 or (http://clienttcpcloud.cloudapp.net/)
Console.WriteLine("\n<<<<<<<<<<<<<<<<<<Server Connected>>>>>>>>>>>>>>>>>>\n");
Console.WriteLine("Sending to Azure...");
Stream s = c.GetStream();
StreamWriter sw = new StreamWriter(s);
sw.WriteLine(text);
sw.Flush();
Console.WriteLine("\n\nGPRS Packet Sent!!!");
s.Close();
c.Close();
I've tried changing the port number to several values, but it still fails to respond. The error that i get is:-
**A Connection failed because the connecting party did not properly respond after a period of time, or the established connection failed, because connected host failed to respond 168.63.239.54:10000**
I really don't know what the problem is.....
There is a sample application at http://blog.maartenballiauw.be/post/2010/01/17/Creating-an-external-facing-Azure-Worker-Role-endpoint.aspx. Have you tried that and compared what it is doing to what you are doing?

How to create TCP client in C# that can recover from server disconnect

I am building a TCP client application in C#. It connects to a server. Under normal conditions the server sends out new data every second. My client application parses the byte stream, saves it to the database and then waits for the next message from the server. It runs on a separate thread and should continue receiving messages and processing them as long as the main application is running. However there may be times where the server goes away or the network connection is temporarily lost, etc. My code needs to be able to recover from that and continue processing server messages if the server comes back online or is again reachable. My current code seems to hang when the server is disconnected and the only way to get it to process again is to shut it down completely and then restart it. What am I doing wrong?
bool IsCancelled = false;
IPEndPoint _ipEndPoint = new IPEndPoint(IPAddress.Parse(myIPAddress), myPort);
TCPClient _tcpClient = new TCPClient();
_tcpClient.Connect(_ipEndPoint);
NetworkStream _networkStream = _tcpClient.GetStream();
while(!IsCancelled)
{
_data = new byte[10025];
if(_networkStream.CanRead)
{
_bytesRead = _networkStream.Read(_data, 0, (int)_tcpClient.ReceiveBufferSize);
if(_bytesRead > 0)
{
...Process data...
}
}
}

Resources