We are developing an App on iOS and Android that includes implementation of socket.io for quick messaging.
For iOS we are using Socket Connection with params, where we send the 'user_id' in configuration and the server receives it.
We are unable to find, the Android implementation of the same scheme.
Following is the iOS code.
// creating dictionary/json to be sent on connection
var dic = NSMutableDictionary()
dic.setValue(["user_id": Profile().getProfile(atr: "_id") as! String], forKey: "connectParams")
// creating socket.io object and passing dictionary into config
socket = SocketIOClient(socketURL: NSURL(string: "http://something.com")!, config: dic as! NSDictionary )
socket!.connect() // works perfectly
I think you have to do like this. Please try it and let me know is it working for you.
Socket socket = null;
try {
IO.Options mOptions = new IO.Options();
mOptions.query = "userId=" + mUserId;
socket = IO.socket(url, mOptions);
} catch (URISyntaxException e) {
return Observable.error(e);
}
socket.connect();
Related
I am trying to make an andorid app that commuicates with my server via Unity 5.4. The Devices need to be in the same network to do so.
For that i am using System.Net.Sockets and a TcpClient to connect to my server. Everything works well when i run it out of the Editor, or build it as a Windows standalone.The communication between a pc hosting the service and a diffrent pc running the standalone is possible and working as intended. As soon as i build it as an .apk and install it on my smartphone i will get a SocketException. Also my phone is stuck loading for quite some time
Is using a TcpClient, is that possible on android with unity3d ?
The Exception i get is:
System.Net.Sockets.SocketException: Connection timed out
I made sure that both devices are in the same network, e.g. the Ip for my Pc hosting the server is 192.168.178.24 and the ip for my smartphone is 192.168.178.113.
The ports required are open and the firewall lets data through.
I am runnig this code in Unity:
private TcpClient client;
private StreamWriter writer;
void Start()
{
try
{
client = new TcpClient(AddressFamily.InterNetwork);
IPAddress ipAddress = IPAddress.Parse(PlayerPrefs.GetString(MenuManager.IpPlayerPrefKey));
Debug.Log(ipAddress.ToString());
client.Connect(ipAddress, 11000);
writer = new StreamWriter(client.GetStream());
Debug.Log("connected");
}
catch (ArgumentNullException ane)
{
Debug.Log(string.Format("ArgumentNullException : {0}", ane.ToString()));
}
catch (SocketException se)
{
Debug.Log(string.Format("SocketException : {0}", se.ToString()));
}
catch (Exception e)
{
Debug.Log(string.Format("Unexpected exception : {0}", e.ToString()));
}
}
i double checked if the Ip adress recieved from the player prefs is correct, it is.
Has someone an idea what causes it to not even establish a connection ? I tried Wireshark on my pc, it didn't show any incoming packages, so my guess is the mistake is sometimes during establishing the connection.
Here is an image for my Log output from the smartphone:
LogCat Output
Edit: Server Code
public class ServiceListener
{
public TcpListener Listener;
public void StartListening()
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = Array.Find<IPAddress>(ipHostInfo.AddressList, ipMatch => ipMatch.AddressFamily == AddressFamily.InterNetwork);
Listener = new TcpListener(ipAddress, 11000);
Listener.Start();
}
public void StopListening()
{
Listener.Stop();
}
}
static void Main()
{
ServiceListener currentListener = new ServiceListener();
currentListener.StartListening();
TcpClient currentClient = currentListener.Listener.AcceptTcpClient();
StreamReader reader = new StreamReader(currentClient.GetStream());
Console.WriteLine("Connected");
while (true)
{
byte[] messageBytes = new byte[1024];
if (!reader.EndOfStream)
{
string message = reader.ReadLine();
string[] messageParts = message.Split('|');
int xOffset = int.Parse(messageParts[0]);
int yOffset = int.Parse(messageParts[1]);
bool leftClick = bool.Parse(messageParts[2]);
bool rightClick = bool.Parse(messageParts[3]);
Console.WriteLine(string.Format("x:{0},y:{1},left:{2},right:{3}", xOffset, yOffset, leftClick, rightClick));
}
else
{
currentClient = currentListener.Listener.AcceptTcpClient();
reader = new StreamReader(currentClient.GetStream());
}
}
}
Is using a TcpClient, is that possible on android with unity3d ?
Yes, it is. It is very possible and should work.
Your problem is very likely to come from this line of code:
IPAddress ipAddress = IPAddress.Parse(PlayerPrefs.GetString(MenuManager.IpPlayerPrefKey));
Since your hosting server IP is 192.168.178.24. Hardcode the value for testing purposes to see if PlayerPrefs.GetString(MenuManager.IpPlayerPrefKey) is returning an invalid IP Address.
Maybe something like:
IPAddress ipAddress = IPAddress.Parse("192.168.178.24");
Another thing to do in your server code is to put Application.runInBackground = true; in your Start() function. This will make sure that your server is running even when the Applciation is not on focus.
Finally, you are currently using synchronous server socket. When connecting, receiving data from the server, Unity will block/freeze until that operation completes. You should use asynchronous socket or run your server and client code in another Thread. This does not look like the current problem but you will run into it later on.
I am trying to send data from my Android phone to my home-server by using sockets. My server runs Linux so I used Perl to code the script for my server. The connection works fine and I can send data to my client running on the phone.
Problem is, when I send something (first try was a simple string) to the server, I don't receive anything at the servers side. Everything works fine if I use telnet to send a string to the server.
I am sitting here for some time now and I looked if there was a similar question to mine and could not find any in which the problem is discussed for Android to Perl-script. Here is my code for the Android app:
try {
Socket socket = new Socket("192.168.178.22", 22222);
Statusinformation("connection with server succeed");
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Statusinformation(input.readLine());
OutputStream outstream =socket.getOutputStream();
PrintWriter out = new PrintWriter(outstream);
out.println("This is a test message from client on phone!\n");
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
Statusinformation("connection unsucsessfull");
e.printStackTrace();
}
on my phone I receive this if i execute the above code:
connection with server succeed!
and on the server side I'm using this code to receive the string from socket clients:
use IO::Socket;
my $server = IO::Socket::INET -> new(
Proto => 'tcp',
LocalPort => 22222,
Listen => SOMAXCONN,
);
print "Server started..\n";
while (1) {
next unless my $conect = $server -> accept();
my $childconection = fork;
if ($childconection == 0) {
handle_connection($conect);
}
}
sub handle_connection
{
my $sock = shift;
my $client_message="";
my $client_addr = $sock -> peerhost;
print "connection: $client_addr connected\n";
print $sock "hi $client_addr, you are connected!\n";
while (1) {
open (Tempfile, '>>tempfile.txt');
while ($client_message = <$sock>) {
print Tempfile $client_message;
print $client_message;
}
close (Tempfile);
}
close($sock);
exit(0);
}
ok now I am a little ashamed.
I solved the problem by adding:
out.flush();
the flush() method assures that all pending data is send to the target and flushs the target.
I have a working ASP.NET Web API service running in Visual Studio on my dev box. I can easily get the proper results from either I.E. or FireFox by entering: http://localhost:61420/api/products. But when trying to read it from my Android Project using my AVD I get an exception thrown saying:
localhost/127.0.0.1:61420 - Connection refused.
I know my Android Java code works because I can access the WCF RESTFul service running on my Website (the URLthat's currently commented out). My Android code is pasted below.
So, why am I getting the error when accessing from my Eclipse project but not when accessing it from a browser?
Thanks
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HttpURLConnection urlConnection = null;
try
{
//URL url = new URL("http://www.deanblakely.com/myRESTService/SayHello");
URL url = new URL("http://localhost:61420/api/products");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String myString = readStream(in);
String otherString = myString;
otherString = otherString + " ";
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
urlConnection.disconnect();
}
}
private String readStream(InputStream is)
{
try
{
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while(i != -1)
{
bo.write(i);
i = is.read();
}
return bo.toString();
}
catch (IOException e)
{
return "" + e;
}
}
}
Visual Studio development web server will only accept connections from the local host and not over the network or other virtual connection. Sounds like AVD is seen as a remote host.
To access the app from anywhere, change the webserver that should be used. Assuming you're using Windows 7 and Visual Studio 2010, make sure you have IIS and all required features installed and set the local IIS as the webserver in your project settings:
It could be necessary to start Visual Studio as a Administrator to run it with local IIS.
Use the actual IP address of your machine ie, http://192.168.0.xx
Only your local machine can access localhost, and if you are on the emulator or a device, it will have a different IP through either NAT or your DHCP from the router.
How can access to wss:// protocol in java ?
i use benkay / java-socket.io.client
but it's not support wss protocol.
i tried use SSLEngine. but it's very hard work.
how can connect to ssl in java ?
I tried change SocketChannel by SSLEngine. but it is not worked.
ssl channel is ok. but i can't wire this original websocket part.
this is source code.
client = SocketChannel.open(remote);
client.configureBlocking(false);
//client.connect(remote);
selector = Selector.open();
this.conn = new WebSocket(client, new LinkedBlockingQueue<ByteBuffer>(), this);
client.register(selector, SelectionKey.OP_READ);
try {
sslClient = new SSLClient(keyStore, storepass.toCharArray(), client);
sslClient.beginHandShake();
startClient()
} catch (Exception e) {
e.printStackTrace();
}
this point uncorret ?? i don't know .. not same the original websocket code.. may problem is this point. how can fix it ??
public void startClient()
{
try
{
while(true)
{
if(selector.select() <= 0)
{
continue;
}
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while(it.hasNext())
{
SelectionKey key = (SelectionKey)it.next();
Log.e("key","key");
if(key.isReadable())
{
read(key);
}
it.remove();
}
}
}
catch(Exception e)
{
}
}
and SSLClient is http://rapidant.tistory.com/attachment/cfile25.uf#121346414D45B0960BD01B.zip
key store : change JKS to BKS, not problem.
how can wrap the SocketChannel ?
(Web browser it worked.)
You could check out my fork of the Autobahn WebSocket Library.
Secure WebSockets based upon Autobahn
You don't want to use SSLEngine on Android because it is broken.
I have created the local host server in android and i am trying to communicate with my ajax call.I successfully connected to the server but unable to receive response.xmlhttp status returns 0 only.if i created the server as the sepa
Ajax call
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
document.getElementById("myDiv3").innerHTML=xmlhttp.readyState+"";
// document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
if (xmlhttp.readyState==4)
{
document.getElementById("myDiv1").innerHTML=xmlhttp.status+"";
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
// document.getElementById("myDiv2").innerHTML="2";
}
xmlhttp.open("GET","http://localhost:8888/Server",true);
//xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
server code
try{
String fromclient;
String toclient;
ServerSocket Server = new ServerSocket (8888);
System.out.println ("TCPServer Waiting for client on port 8888");
while(true)
{
Socket connected = Server.accept();
System.out.println( " THE CLIENT"+" "+
connected.getInetAddress() +":"+connected.getPort()+" IS CONNECTED ");
PrintWriter outToClient =
new PrintWriter(
connected.getOutputStream(),true);
outToClient.write("<html><head>hai</head></html>");
connected.close();
}
}
catch(Exception e)
{
}
}
The term "localhost" is not correct at all here. "Development machine" or "host machine" would me more accurate.
Anyway, change:
xmlhttp.open("GET","http://localhost:8888/Server",true);
and use:
xmlhttp.open("GET","http://10.0.2.2:8888/Server",true);
Remember to check your firewall/iptables and all that stuff. I didn't check your code for any other error but this should do the trick regarding the connection.