CONTEXT:
I am creating a cross-platform multicast client-server system for mobile. I have created the server side in Java. I also created the android client side and it works perfectly.
WHAT I WANT TO KNOW:
I want to know if I could create a client side in iOS using the listener program in this example http://ntrg.cs.tcd.ie/undergrad/4ba2/multicast/antony/example.html that would be compatible with my server-side that I created in Java.
If the above example will not work is there a way I can still use my Java server-side and create a native iOS client system that is compatible with the Java server-side?
SAMPLE CODE OF JAVA SERVER SIDE FOR REFERENCE:
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
//more imports...
class Server2 {
public static MulticastSocket ms1;
public static void main(String[] args) throws IOException {
try {
InetAddress sessAddr1 = InetAddress.getByName("224.2.76.24");
ms1 = new MulticastSocket(5500);
ms1.joinGroup(sessAddr1);
while(true) {
byte[] message = new byte[1024];
message = getIpAddress().getBytes();
DatagramPacket dp = new DatagramPacket(message, message.length, sessAddr1, 5500);
ms1.send(dp);
System.out.println(String.format("Sent message: %s", message));
Thread.sleep(1000);
}
} catch (Exception e) {
System.out.println(String.format("Error: %s", e));
}
}
public static String getIpAddress() {
InetAddress ip;
try {
ip = InetAddress.getLocalHost();
return(String.format("%s",ip.getHostAddress()));
} catch (Exception e) {
return("false");
}
}
}
I tested the listener code in the link and it worked perfectly.
Should not be a problem. iOS is POSIX compliant and Objective-C is defined on top of ANSI C, so you could paste the code you linked to with minor modifications straight into your project, build a simple wrapper to Objective-C and your app should compile, run and work as desired.
Related
I am trying to create a socket connection between a .Net server application and Java Client Application.
I am getting an error from the java client application:
Connection refused: connect
Notes:
Communicating with a .Net Client Application, works fine.
I have disables the windows firewall
Undoubtedly, I am running the server application in the background and then I am running the client application
Following are my server code (C#):
public class Server
{
public Server()
{
CreateListener();
}
public void CreateListener()
{
// Create an instance of the TcpListener class.
TcpListener tcpListener = null;
IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
string output;
try
{
// Set the listener on the local IP address
// and specify the port.
tcpListener = new TcpListener(ipAddress, 13);
tcpListener.Start();
output = "Waiting for a connection...";
}
catch (Exception e)
{
output = "Error: " + e.ToString();
MessageBox.Show(output);
}
}
}
and client application code (Java):
public class smtpClient {
public void Send() {
Socket smtpSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
try {
smtpSocket = new Socket("localhost", 13); // FAILURE
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host: hostname");
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
It fails at the following line in the Java Client Application:
smtpSocket = new Socket("localhost", 13);
I can't tell what is the issue you are facing, but you need to start with a solid foundation to discover these issues.
As a rule of thumb, you should always write one piece (typically the server) first and verify connectivity (say using telnet) and then write the other piece (typically client) and verify its connectivity.
I always keep a Standard Client and Server handy to test whether its my code or its the environment/configuration.
Below is a sample code that works fine to test connectivity.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
class ClientServer {
static void Main() {
new Thread(() => { StartServer("localhost", 5013); }).Start();
Thread.Sleep(100);
Console.WriteLine("\nPress enter to start the client...");
Console.ReadLine();
StartClient("localhost", 5013);
}
public static void StartServer(string serverInterface, int port) {
try {
IPHostEntry hostInfo = Dns.GetHostEntry(serverInterface);
string hostName = hostInfo.HostName;
IPAddress ipAddress = hostInfo.AddressList[0];
var server = new TcpListener(ipAddress, port);
server.Start();
Console.WriteLine($"Waiting for a connection at {server.LocalEndpoint}");
Console.WriteLine("Press ctrl+c to exit server...");
while (true) {
TcpClient client = server.AcceptTcpClient();
Console.WriteLine($"Server says - Client connected: {client.Client.RemoteEndPoint}");
ThreadPool.QueueUserWorkItem((state) => {
using (var _client = (TcpClient)state)
using (NetworkStream stream = _client.GetStream()) {
string msg = stream.ReadAsciiData();
if (msg == "Hello!") {
stream.WriteAsciiData($"Time:{DateTime.Now: yyyy/MM/dd HH:mm zzz}. Server name is {hostName}");
}
}
}, client);
}
} catch (Exception e) {
Console.WriteLine(e);
}
}
public static void StartClient(string serverInterface, int port) {
Console.WriteLine("Client started...");
try {
using (var client = new TcpClient(serverInterface, port))
using (NetworkStream stream = client.GetStream()) {
Console.WriteLine("Client says - Hello!");
stream.Write(Encoding.ASCII.GetBytes("Hello!"));
string msg = stream.ReadAsciiData();
Console.WriteLine($"Client says - Message from server: Server#{client.Client.RemoteEndPoint}: {msg}");
}
} catch (Exception e) {
Console.WriteLine(e);
}
Console.WriteLine("Client exited");
}
}
static class Utils {
public static void WriteAsciiData(this NetworkStream stream, string data) {
stream.Write(Encoding.ASCII.GetBytes(data));
}
public static string ReadAsciiData(this NetworkStream stream) {
var buffer = new byte[1024];
int read = stream.Read(buffer, 0, buffer.Length);
return Encoding.ASCII.GetString(buffer, 0, read);
}
public static void Write(this NetworkStream stream, byte[] data) {
stream.Write(data, 0, data.Length);
}
}
Now to your specific problem,
The choice of port 13, is not ideal for testing. Usually all ports below 1024 are considered privileged. i.e. a firewall or antivirus might block your attempt to listen on that port
Remember that IPV6 addresses plays a role. Your machine might have that enabled or disabled based on your configuration. You want to make sure that if your server is listening on a IPv6 interface, then your client also connects on the same
Which brings us to another related point: Irrespective of you are using IPv6 interface or not, the client needs to connect to the same interface the server is listening on. This might seem obvious, but is often missed. A typical machine
has at-least 2 interfaces: One for localhost (127...* called loopback interface) and another non local (typically 10...* or 192...*, but not restricted to it). It can so happen (especially when you pick the first available interface to bind your server without knowing which one it is) that server might be listening on non loopback interface like say 192.168.1.10 interface and the client might be connecting to 127.0.0.1, and you can see why the client will get "connection refused" errors
The sample code above works and you can test your code with it. You can us telnet for a client or just my sample code. You can play around changing the serverInterface values to some surprising discoveries which are accentuated by
ipAddress = hostInfo.AddressList[0] line
Hope this helps you with your debugging
I'm able to create docker container for ACE-TAO service , and able to access it from parent windows machine using port-forwarding concept.
From browser i try to hit the localhost:forward-port and getting "ERR_EMPTY_RESPONSE" and TAO service is running in docker container.
If I want to verify in local, whether its connected properly or not.
How can I write Java code to verify?
The following java code connects to localhost:17500 and prints out a message saying whether or not it could create a tcp connection.
import java.io.*;
import java.net.*;
class TCPClient
{
public static void main(String argv[]) throws Exception
{
try {
Socket clientSocket = new Socket("localhost", 17500);
System.out.println("Could connect");
}
catch (ConnectException e) {
System.out.println("Cannot connect");
}
}
}
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.
I want my Java application to send and receive SMS without using any additional hardware devices and it must be free.
I made my search but all i found is titles, i found somethings like SMSLib but at the other hand i didn't find tutorials or books to learn that.
I also found that SMSLib code but didn't understand:
Send Message/SMS Code
package SMSEngine;
import org.smslib.*;
class SendMessage
{
public static void sendMessage(String number, String message)
{
CService srv = new CService("COM4",9600,"huawei","E220");
try
{
srv.setSimPin("0000");
srv.setSimPin2("0000");
srv.setSmscNumber("");
srv.connect();
COutgoingMessage msg = new COutgoingMessage(number, message);
msg.setMessageEncoding(CMessage.MessageEncoding.Enc7Bit);
msg.setStatusReport(true);
msg.setValidityPeriod(8);
srv.sendMessage(msg);
srv.disconnect();
}
catch (Exception e)
{
e.printStackTrace();
}
System.exit(0);
}
}
Read Message/SMS Codes
package SMSEngine;
import org.smslib.*;
import java.util.*;
class ReadMessages
{
static CService srv;
public static LinkedList receiveMessage()
{
LinkedList msgList = new LinkedList();
/*
To Check COM port Go in following path in Windows7
Control Panel\Hardware and Sound\Bluetooth and Local COM
*/
srv = new CService("COM4",9600,"huawei","E220");//"COM1", 57600, "Nokia", ""
try
{
srv.setSimPin("0000");
srv.setSimPin2("0000");
srv.connect();
srv.readMessages(msgList, CIncomingMessage.MessageClass.Unread);
srv.disconnect();
return msgList;
}
catch (Exception e)
{
e.printStackTrace();
}
System.exit(0);
return msgList;
}
}
In order to send SMS messages you have two options: either use a gateway modem, or use a bulk service with an online API.
SMSLib is only a library that makes it easier to interface with a gateway (hardware device) or with a bulk SMS provider. Either way, the library by itself is not enough.
The code sample that you provided appears to try to use a gateway connected to a local serial port but since you don't have such a hardware device it's not going to work for you.
One way is to use SMS gateway and send them like ordinary emails.
"I also found that SMSLib code but didn't understand"-
Assuming that you know java/object oriented programming, read through an online tutorial on smslib for understanding the basics. May be you can start with this one http://smslib.org/doc/smslib/quickstart/
On my machine, the following code compiles within Eclipse but throws an exception within Netbeans. The error message says "Exception in thread "main" java.net.BindException: Address already in use".
What is the proper configuration within Netbeans to make this code compile? It seems like the problem has to do with the fact that I have two main functions. If I start running either one of the apps, the second will fail to start, throwing the exception posted above.
Server.java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
Server myServ = new Server();
myServ.run();
}
public void run() throws Exception {
ServerSocket mySS = new ServerSocket(9999);
Socket SS_accept = mySS.accept();
InputStreamReader mySR = new InputStreamReader(SS_accept.getInputStream());
BufferedReader myBR = new BufferedReader(mySR);
String temp = myBR.readLine();
System.out.println(temp);
}
}
Client.java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws Exception {
Client myCli = new Client();
myCli.run();
}
public void run() throws Exception {
Socket mySkt = new Socket("localhost", 9999);
PrintStream myPS = new PrintStream(mySkt.getOutputStream());
myPS.println("Hello server");
}
}
The problem is due to the fact that you left one instance of your server running and then started another one.
The way to achieve what I want is to right-click on the particular class (ex. Server.java) that I want to run and select "Run this file". This enables me to run only the Server app. Then, do the same process for the other file, Client.java.
However, Netbeans is somewhat confusing/deceiving in this particular circumstance. What Netbeans does is it runs the Server process, but labels that process as the name of the project (ex. MyTestNetworkingProject) and puts a run number on it, thus giving us MyTestNetworkingProject run #1 (it actually leaves out the #1 on the first process). Then, if I go to the Client.java file and select "Run this file", it generates a second process, MyTestNetworkingProject run #2. It then generates a second results window down at the bottom of the screen, as it generates these in new tabs as new processes get created.
Because of the nature of my specific code, what I wanted to see in my results window to confirm that my application was working was I wanted to observe the Server.java results window (which in this case is MyTestNetworkingProject run #1). Given my exact sequence of steps outlined above of running the different files, run #2 is the last run process and thus the tab on top, covering the run #1 tab. I can click on run #1 and see the results I was hoping to see in the console ("Hello server"), but I just have to know/remember that MyTestNetworkingProject run #1 represents the Server app and not the Client app.
Uncool, IMO.
If you write this in Windows OS,you can use "netstat -nao" to see which process use the 9999 port.If it is some unimportant process,you can kill this process.Otherwise you can change the port of the pragram.
I change the port address and it work for me in the Neat Beans IDE . This problem will come if we used the same port address for other one times . so to fix this error you have to change the port address and I am sure it will work
Server.java
public class SocServer {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(5001);
Socket client = server.accept();
DataOutputStream os = new DataOutputStream(client.getOutputStream());
os.writeBytes("Hello Sockets\n");
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client.java
public class SocClient {
public static void main(String[] args) {
try {
Socket socClient = new Socket("localhost", 5001);
InputStream is = socClient.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String receivedData = br.readLine();
System.out.println("Received Data: " + receivedData);
} catch (IOException e) {
e.printStackTrace();
}
}
}
refer above code and it works for me..
I did try the method catch and solved the problem.