I am new and I've a question.
In android, I can't connect any remote address via TCP Socket. When I tried to connect, debugger shows an error:
Exception: failed to connect to /23.20.47.114 (port 9339) after 2000ms: connect failed: EINVAL (Invalid argument), OSVersion: 4.1.1(Jellybean)
And the code:
void run(){
Socket s=new Socket();
s.bind(getAddress("192.168.0.45",8080)); <-It's bound successfully.
s.connect(getAddress("23.20.47.114",9339)); <-Error
writeData(s);
}
InetSocketAddress getAddress(String host, int port){[code]}
void writeData(Socket so){[code]}
Note: This server is always open and sorry for my english.
You already bound the socket to a local IP address using bind(), so it does not make sense to also connect the same socket to a remote server. Try getting rid of the bind() statement.
Related
I'm developing an application on android studio. I'm trying to open a socket connection.
When the user enters the right IP address, everything works fine, but if the address is not the right IP, the Socket is not connected.
But the problem is that the Socket does not throw an catch Exception, the app is running and now if the user enters the right ip address, the socket is not connected.
My question is why it does not throw an catch Exception if the IP address is not the right IP and how can I make it work?
Here is the code
try {
sockettcp = new Socket(Address, Port);
} catch (Exception e) {
valid = false;
}
Normal way of Socket is that it tries to connect to the given IP on the given Port.
If for some reason the IP is not the right one, the Socket will not throw an err, instead it will "timeout" trying to reconnect every minute or so (Main thread or the GUI thread).
The 4 errors that are Thrown by this type of constructor public Socket(String host, int port) are:
IOException //- if an error occurs during the connection
SocketTimeoutException //- if timeout expires before connecting
IllegalBlockingModeException //- if this socket has an associated channel, and the channel is in non-blocking mode
IllegalArgumentException //- if endpoint is null or is a SocketAddress subclass not supported by this socket
To "Fix" your problem, you can set the timeout to your value (this cannot exceed the platform default)
Socket sck = new Socket();
sck.connect(new InetSocketAddress(ip, port), timeout);
To "Check" if your Socket is connected, you could try this:
Socket.isConnected(); //Returns the connection state of the socket.
Note: Closing a socket doesn't clear its connection state, which means this method will return true for a closed socket (see isClosed()) if it was successfully connected prior to being closed.
See the javadoc for more info about theSocket.
I'm stuck at a homework assignment for my university course.
We are supposed to write a game of Rock-Paper-Scissors using Client and Server, choosing TCP or UDP.
The assignment for the client part is:
"Get the IP-address and port of the server at the beginning and than use this information to connect to the server."
And server:
"The port needs to be set to a number between 10000 and 20000 at the start using command line input."
Now this got me wondering. How is the Client supposed to get the Ip-Adress and port of the server if it is not connected to the server yet?
And normally the client and the server creates a socket and the server listens if a client wants to connect and then accepts the request, making a connection, not the client, like it is requested in the assignment. Isn't it impossible to know the server, if not connected yet?
I got a version working, if the server goes:
// Setting the port via console, making an output: "please enter valid port" and returns the entered port number
ServerTest.port = ServerTest.getPort();
...
ServerSocket testSocket = new ServerSocket(ServerTest.port);
and the client:
private static String host = "localhost";
private static Integer port = 1337;
...
Socket clientSocket = new Socket(ClientTest.host, ClientTest.port);
if I set the port to 1337 when starting the server.
Then I tried something like
//Client
port = ServerTest.getServerPort();
...
Socket clientSocket = new Socket(ClientTest.host, ClientTest.port);
and in the server-class:
public static Integer getServerPort(){
return port;
}
But that throws an "Connection refused"-exception, even if I first the server at first, set the port and than start the client.
Does anyone have an idea how to solve this?
I'm attempting to connect to a TCP socket in Android.
I know the socket service works because I can connect and interact with it in a browser (in JavaScript) as follows:
var ws = window.WebSocket || window.MozWebSocket;
window.ws = new wsImpl('ws://foo.bar.com:8282/MySocketService', 'my-protocol');
...
So, in my Android app:
This connects successfully, but I never receive messages from it:
SocketAddress sa = new InetSocketAddress("foo.bar.com", 8282);
This fails to connect:
SocketAddress sa = new InetSocketAddress("foo.bar.com/MySocketService", 8282);
and I receive an error like:
java.net.UnknownHostException: Host is unresolved: foo.bar.com/MySocketService:8282
Is there any way to indicate the application path for a TCP service?
TCP end-point is just IP address and a port number. What you are talking about is handled by upper-level protocols on top of TCP, like HTTP, so you need to look at other utilities like java.net.URL.
Very stuck on this one, so I appreciate any help you can give!
I have two programs, an Android app and a multi-socket Java server. The Android app first establishes an outbound connection to the server (port 21) then accepts in inbound connection from the server (port 1025). For consistency I'll always call the Android app the client and the Java app the host, regardless of the direction the connection is being established in.
The programs work perfectly on a local network, with either my android phone connecting to my local server ip 192.168.1.103 or the emulator on the PC hosting the server connecting to 10.0.2.2.
However when I move outside of my local intranet, I can still establish the android->server connection on port 21 but I time out trying to connect from the server to the phone on port 1025.
A list of things I am accounting for:
Android emulator has port 1025 redirected
Windows (Win 7 server host) firewall is disabled, other known firewalls are disabled
The incoming connection listener is not on the main thread (SDK 2.1 so shouldn't matter)
Router ports 21 and 1025 are being forwarded
A list of tests and their outcomes:
Connecting to server's public ip (router present) from emulator/android phone on local network/android phone on remote network - fails to establish server->phone connection
Removing router and connecting from emulator or remote android phone - fails to establish server->phone connection
Connecting from emulator to 10.0.2.2, router present or not - succeeds
Connecting from android phone on local network to 192.168.1.103 - succeeds
And finally some code, the Servers's output connection attempt (connection is created in the constructor since a sub-thread for this client was already created upon the server's receipt of an inbound connection)
OutputSocketServer(InetAddress inetAddress, int port, int count , LinkedBlockingQueue<Packet> outQueue) {
this.outQueue = outQueue;
SocketAddress sockaddr = new InetSocketAddress(inetAddress,port);
try {
outConnection = new Socket();
System.out.println("Connecting to " + sockaddr.toString());
outConnection.connect(sockaddr, timeout);
System.out.println("Connected to port " + outConnection.getPort() + " of " +outConnection.getInetAddress().toString() + " from local port " + outConnection.getLocalPort());
osw = new ObjectOutputStream(outConnection.getOutputStream());
} catch (IOException e) {
System.out.println("Output Socket Server: Could not establish outbound connection" + e.toString());
e.printStackTrace();
}
}
and the relevant part of the Android Client's connection accept code
public void run() {
try {
System.out.println("Listening for connection on local port " + inSocket.getLocalPort());
this.inConnection = inSocket.accept();
System.out.println("Accepted connection on port " + inConnection.getPort() + " from ip " + inConnection.getInetAddress().toString());
isr = new ObjectInputStream(inConnection.getInputStream());
}
catch (Exception e) {
System.out.println("Inbound Socket Server: " + e.toString());
}
}
The stack trace for the android client just says SocketTimeoutException: operation timed out and for the server ConnectException: connection refused: connect. Prior to that the client's LogCat shows Listening for connection on port 1025 and the server Connecting to /my.ip.he.re:1025
Thanks for any guidance!
Most wireless services assign only non-routable RFC1918 addresses to devices, and route "the internet" through NAT. That means your device can make outbound connections - but you cannot connect to it from the outside (inbound). One reason is the lack of free IPv4 address space.
Since your post mentions Port 21: If you want FTP, use passive mode. In this mode the Android device will make the data connection to the server.
I am going to create a socket and get an InputStream. Here is how I try it.
try {
final String serverIP = "111.111.111.111";
final int serverPort = Integer.parseInt(server_port);
final InetAddress serverAd=InetAddress.getByName(serverIP);
final InetAddress localAd =InetAddress.getByName(local_ip);
final int localPort = 4040;
Socket socket = new Socket(serverAd, serverPort, localAd, localPort);
}
But there is an exception thrown,
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:276)
at shootist.Porter.run(Porter.java:41)
Here the server sends me rtp data and server side is ok and confirmed. I sent invite and got 200 as well. If there is a problem in my IP and port, I think, all responses cannot delivered to my IP and given Ports. But it can't happen as the server sends me responses to my IP and given port number.
How I can fix this issue? Where I am wrong and what?
A "connection refused" error means the socket stack on the server machine received your connection request and intentionally refused to accept it. That happens for one of two possible reasons:
1) there is no listening socket running on the port you are trying to connect to.
2) there is a listening socket, but its backlog of pending connections is full, so there is no room to queue your request at that moment.
To differentiate between the two, try reconnecting a few times with a delay in between each attempt. If you get the same error consistently, then #1 is likely the culprit. Make sure the port number is correct. If #2 is the culprit, your reconnect has a chance of succeeding eventually.
Connection refused means your are try to connect to a server which is not listening on that port, or is too backlogged to accept the connection.
A simple way to test this is to try
telnet 111.111.111.111 4040