Android and Java Socket don't have the same behavior - java

I'm using Java to implement some socket programs.
I found that both of Android and Java have java.net.Socket, but the source code are not the same, so that they have different behavior.
I have a server(maybe PC or Android), and the server has multiple network interface(E.g. Ethernet, Wireless, USB or Bluetooth). The client will try to connect all the server network interface at the same time(one connection one thread). Until the client finds an available connection, they will communicate via the connection. In this way, I expect that the connection speed will not too low.
But when the client is trying to connect to server, it may encounter a repeat-connect situation in Android device(Android SDK). If the program encounter the repeat-connect situation, the previous connection will be reset or be replaced(I'm not sure) by the latter connection. At the same time, when reading or writing the previous connection, it will throw java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer). In the other hand, when reading or writing the latter connection, it is normal, but the connection speed is not very fast.
This problem seems to not be happened on PC but happened on Android when the client is trying to connect to server.
How can I solve it?
EDIT
The client code as below:
private Socket socket;
private IP ip;
private IP[] IPs;
private boolean closing;
private int socketTriedCount;
...
socketTriedCount = 0;
for (final IP ipObj : IPs) {
if (closing) {
break;
}
new Thread() {
#Override
public void run() {
try {
if (socket == null) {
final Socket s = new Socket();
s.connect(new InetSocketAddress(InetAddress.getByName(ipObj.getIP()), ipObj.getPort()), timeout);
synchronized (Client.this) {
if (socket != null) {
//Should not be happened
//s.close();
socketTriedCount++;
} else {
ip = ipObj;
socket = s;
socketTriedCount++;
}
}
}
} catch (final Exception ioE) {
socketTriedCount++;
}
}
}.start();
}

Related

Java : Opening client socket

I work on a java application.
I got a java socket server mapped with a #ServerEndpoint("/wsock")
Form my javascript code I access the WebSocket from this URL :
ws://192.9.200.73:8084/socketserver/wsock
I want now access to this socket from my java code. But how can I specify the address "socketserver/wsock" ? I've tried something but I got every time an error message.
This is my test :
Socket s = new Socket("localhost/socketserver/wsock", 8084);
But it doesn't work, I got everytime an error message: ".UnknownHostException: localhost/socketserver/wsock"
Any idea?
Thank's
public static boolean pingHost(String host, int port, int timeout) {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(host, port), timeout);
return true;
} catch (IOException e) {
return false; // Either timeout or unreachable or failed DNS lookup.
}
}
Try this. Its something like ping. If you get true its connected. But your server should be ready.
You use a Websocket client. You can't use a Socket directly for this. There is a superimposed protocol.

Android socket connection errror : connect failed: ETIMEDOUT

I am developing an android app, that will be communicating with an wifi controler (fixed IP and PORT) using TCP , but since i don't have the controller yet. So i created a simple C# server programm that would recieve some test messages.
But when i try to open the connection in android, it gives me the Exception:
java.net.ConnectException: failed to connect to /10.0.2.2 (port 1234): connect failed: ETIMEDOUT (Connection timed out)
C# Program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Server
{
class Program
{
static byte[] Buffer { get; set; }
static Socket sck;
static void Main(string[] args)
{
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sck.Bind(new IPEndPoint(0, 1234));
sck.Listen(100);
Socket accepted = sck.Accept();
Buffer = new byte[accepted.SendBufferSize];
int bytesRead = accepted.Receive(Buffer);
byte[] formatted = new byte[bytesRead];
for (int i = 0; i < bytesRead; i++)
{
formatted[i] = Buffer[i];
}
string strData = Encoding.ASCII.GetString(formatted);
Console.Write(strData + "\r\n");
Console.Read();
sck.Close();
accepted.Close();
}
}
}
Android code:
try
{
if (socket == null) {
int SERVERPORT = 1234;
InetAddress serverAddr = InetAddress.getByName("10.0.2.2");
socket = new Socket(serverAddr, SERVERPORT); // FAILS
}
}
} catch (IOException e) {
e.printStackTrace();
}
Its the first time i had to work with sockets. And i am DUMB when it comes to networking things. So it probably is a simple error.
Of course i checked all the related questions with this error, but still couldnt figure this out.
I am using GenyMotion Emulator.
Using Windows 8.1 64x.
I set the firewall settings to allow the C# app to communicate throgh windows firewall (public and private).
Does anyone know the solution? Thanks

How to figure out to which server a client connected to

I'm using Netty to build a client-server network communication. Is it possible to find out to which app a client has connected to in case of success?
It's the following problem I try to solve: If a Tomcat Server is listening to port 8080 my client app successfully connects to the "server". Looks like it doesn't matter who is listening to the port.
How can I find out if my server app is currently started and listening to the port instead of e.g. Tomcat?
This is the connection code of the client:
public void run(){
//disconnectTest();
createBootstrap( new Bootstrap(), new NioEventLoopGroup(), true);
}
public void createBootstrap( Bootstrap b, EventLoopGroup eventLoop, boolean initialAttempt){
mWorkerGroup = eventLoop;
try {
b.group(mWorkerGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
.handler(new ClientChannelInitializer());
logger.info("Connecting client...");
b.connect(mHost, mPort)
.addListener( new ConnectionListener(this, initialAttempt));
} catch (Exception e) {
logger.error("Failed to connect client to server '" +mHost +": " +mPort +". Error: ", e);
}
}
Snippet from the ConnectionListener:
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
System.out.println("success");
}else{
System.out.println("error");
}
}
EDIT:
If you want check the availability of the server withing the client App, you can use certain tools that Java7 can give us, for example, using this code:
private static boolean available(int port) {
try (Socket ignored = new Socket("localhost", port)) {
return false;
} catch (IOException ignored) {
return true;
}
}
This does not have to be a specific function Netty. More info here:
Sockets: Discover port availability using Java
Enjoy.
To check it outside you client app:
To test the server status I use the Hercules software client.If you know that server will respond someting, using hercules you can send a dummy data y wait the server response.
How you can see, Hercules, allows too makes a ping to the server :)
Hope it helps.

Client-Server Program, can connect from Java client but not from Android

I have a working Java client/server program which is very straightforward and basic. This works fine. However, I am now trying to write an Android client, and I have been unable to connect to the server from my android client. I am using almost identical code for the android networking code as I use for the normal client. My android code is simple, all it does is starts this thread from onCreate:
private int serverPort = 8889;
private String serverIP = "192.168.5.230";
private Socket socket = null;
private Thread clientThread = new Thread("ClientThread") {
#Override
public void run() {
try {
socket = new Socket();
socket.connect(new InetSocketAddress(serverIP, serverPort), 1000);
DataInputStream din = new DataInputStream( socket.getInputStream());
DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
while (true) {
String message = din.readUTF();
setPicture("picture1");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
The port is the correct port my server is running on, as is the ip address (which I got from ifconfig since I know you cannot use localhost). When I run my normal pc client with the same port and IP address, the connection goes through. But when I run this code on my android device, the socket timesout when I try to connect.
Does anyone have any suggestions for where I am going wrong?
Double check that you added the permission requirement in the manifest file:
<uses-permission android:name="android.permission.INTERNET" />
But, possibly more importantly, 192.168.x.x is a local or non-routable network so you need to be on the same network, or one that knows how to reach the 192.168.5.230 address. You say that it doesn't work when you try it on your device -- are you running on local wifi when you run or are you on your mobile network? If you're on mobile, try it from wifi.

Java Networking "Connection Refused: Connect"

I have been trying to get a simple networking test program to run with no results.
Server:
import java.io.*;
import java.net.*;
public class ServerTest {
public static void main(String[] args) {
final int PORT_NUMBER = 44827;
while(true) {
try {
//Listen on port
ServerSocket serverSock = new ServerSocket(PORT_NUMBER);
System.out.println("Listening...");
//Get connection
Socket clientSock = serverSock.accept();
System.out.println("Connected client");
//Get input
BufferedReader br = new BufferedReader(new InputStreamReader(clientSock.getInputStream()));
System.out.println(br.readLine());
br.close();
serverSock.close();
clientSock.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
Client:
import java.io.*;
import java.net.*;
public class ClientTest {
public static void main(String[] args) throws IOException {
final int PORT_NUMBER = 44827;
final String HOSTNAME = "xx.xx.xx.xx";
//Attempt to connect
try {
Socket sock = new Socket(HOSTNAME, PORT_NUMBER);
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
//Output
out.println("Test");
out.flush();
out.close();
sock.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
The program works just fine when I use 127.0.0.1 or my internal IP for the hostname. But whenever I switch to my external IP address, it throws a java.net.ConnectException: Connection refused: connect error.
I purposely picked such an uncommon port to see if that was the problem, with no luck.
I can connect with no problems using telnet, but when I try to access the port with canyouseeme.org, it tells me the connection timed out.
I even tried to disable all firewalls and antivirus including the Windows default ones and the router firewall, with all ports forwarded and DMZ enabled, and it still says that the connection timed out. I use Comcast as my ISP, and I doubt that they block such a random port.
When I use a packet tracer, it shows TCP traffic with my computer sending SYN and receiving RST/ACK, so it looks like a standard blocked port, and no other suspicious packet traffic was going on.
I have no idea what is going on at this point; I have pretty much tried every trick I know. If anyone know why the port might be blocked, or at least some way to make the program work, it would be very helpful.
These problem comes under the following situations:
Client and Server, either or both of them are not in network.
Server is not running.
Server is running but not listening on port, client is trying to connect.
Firewall is not permitted for host-port combination.
Host Port combination is incorrect.
Incorrect protocol in Connecting String.
How to solve the problem:
First you ping destination server. If that is pinging properly,
then the client and server are both in network.
Try connected to server host and port using telnet. If you are
able to connect with it, then you're making some mistakes in the client code.
For what it's worth, your code works fine on my system.
I hate to say it, but it sounds like a firewall issue (which I know you've already triple-checked) or a Comcast issue, which is more possible than you might think. I'd test your ISP.
Likely the server socket is only being bound to the localhost address. You can bind it to a specific IP address using the 3-argument form of the constructor.
I assume you are using a Router to connect to Internet. You should do Port Forwarding to let public access your internal network. Have a look at How do you get Java sockets working with public IPs?
I have also written a blog post about Port forwarding, you might wanna have a look :) http://happycoders.wordpress.com/2010/10/03/how-to-setup-a-web-server-by-yourself/
But I still couldn't get this accessed over public IP, working on it now...
I had the same problem because sometimes the client started before server and, when he tried to set up the connection, it couldn't find a running server.
My first (not so elegant) solution was to stop the client for a while using the sleep method:
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
I use this code just before the client connection, in your example, just before Socket sock = new Socket(HOSTNAME, PORT_NUMBER);
My second solution was based on this answer. Basically I created a method in the client class, this method tries to connect to the server and, if the connection fails, it waits two seconds before retry.
This is my method:
private Socket createClientSocket(String clientName, int port){
boolean scanning = true;
Socket socket = null;
int numberOfTry = 0;
while (scanning && numberOfTry < 10){
numberOfTry++;
try {
socket = new Socket(clientName, port);
scanning = false;
} catch (IOException e) {
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
return socket;
}
As you can see this method tries to create a socket for ten times, then returns a null value for socket, so be carefull and check the result.
Your code should become:
Socket sock = createClientSocket(HOSTNAME, PORT_NUMBER);
if(null == sock){ //log error... }
This solution helped me, I hope it helps you as well. ;-)

Categories

Resources