android open socket crashing on device, works on AVD - java

i try creating client-server app using socket.
i already succeed doing that with the AVD and run both server and client on my pc machine.
but when i try make it work in same Wifi network on my device, the app just crash.
yes, i'm using seperate thread for the connection
and already added the use of Internet to the manifest.
here is some code...
the client thread:
package com.mainlauncher;
import java.io.*;
import java.net.*;
public class ConnectionThread extends Thread {
private static final int SERVERPORT = 7777;
private static final String SERVERADDRESS = "My-PC";
private Socket socket;
private DataInputStream in;
private DataOutputStream out;
#Override
public void run() {
super.run();
open();
close();
}
void open(){
try{
socket = new Socket(SERVERADDRESS,SERVERPORT);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
}
catch(IOException e){}
}
void close(){
try {
if(in!=null)
in.close();
if(out!=null)
out.close();
if(socket!=null)
socket.close();
}
catch (IOException e) {}
socket=null;
}
}
the Server side main:
import java.io.IOException;
import java.net.*;
public class Main {
public static void main(String[] args) {
int port = 7777;
new Main().handleClients(port);
}
private void handleClients(int port) {
ServerSocket serverSocket = null;
try{
serverSocket = new ServerSocket(port);
System.out.println("Server is ready...");
for(int i=1; ; i++){
Socket socket = serverSocket.accept();
ServerThread thread = new ServerThread(i,socket);
System.out.println(i + " Connected");
thread.run();
}
}
catch (Exception e){
System.err.println(e.getMessage());
}
finally{
if(serverSocket != null){
try{ serverSocket.close(); }
catch(IOException x){}
}
}
}
}
and the ServerThread:
import java.io.*;
import java.net.*;
public class ServerThread extends Thread {
private int serverIndex;
private Socket socket;
private DataOutputStream out;
private DataInputStream in;
public ServerThread (int serverIndex, Socket socket){
this.serverIndex = serverIndex;
this.socket = socket;
}
#Override
public void run() {
super.run();
try {
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
System.out.println(serverIndex + " Disconnected");
}
finally{
try {
in.close();
out.close();
socket.close();
} catch (IOException e) {}
}
}
}
i tried looking for answers here \ google etc...
nothing helped.
there is no firewall or anything to block the incoming connection on my pc.
any ideas anyone?
thanks,
Lioz

This won't immediately solve your problem, but you have a couple of bugs that are causing your program to throw away the evidence of the the real problem.
1) This simply squashed the exception, throwing away all evidence that it ever happened.
catch(IOException e){}
2) This is a bit better, but it only prints out the exception message ... not the stack trace.
catch (Exception e){
System.err.println(e.getMessage());
}
The other problem with 2) is that it catches ALL exceptions ... not just IOExceptions. That includes unchecked exceptions like NullPointerException, SecurityException and so on.
Exceptions should be diagnosed like this:
catch (IOException e){
e.printStackTrace();
}
or logged.
Finally, the way that you are handling requests is wrong:
Socket socket = serverSocket.accept();
ServerThread thread = new ServerThread(i,socket);
System.out.println(i + " Connected");
thread.run();
The mistake is in the last statement. What this actually does is to simply call the thread object's run() method ... in the current thread. To run the run() method in a different thread you need to call the start method. Like this:
Socket socket = serverSocket.accept();
ServerThread thread = new ServerThread(i,socket);
System.out.println(i + " Connected");
thread.start();

Related

java.net.SocketException: Socket is closed between Socket.accept() and Socket.getInputStream()

I'm trying to create a client/server connection and am still quite new to java as well. So the error I am getting tells me that the socket is closed. Following some work, I've managed to write the given code below. I do believe there is something wrong with the way I pass the socket to the connection class, if I had to guess, that causes the socket object to possibly be closed?
I've tried adding waits just in case the server thread hadn't been executed but that didn't seem to affect anything. Maybe I should launch the server with its own launcher in its own command prompt, but I thouht this should work just fine to test the client and server.
I can't seem to find out why my socket is closed before I send my message. Any insights would be greatly appreciated!
Thanks!
Error
java.net.SocketException: Socket is closed
at java.net.Socket.getInputSTream(Unknown Source)
at Connection.run(Connection.java:17)
Server.java
//main calling snippet.
import java.lang.Thread;
public class Server {
public static void main(String[] args) {
if(args.length != 1) {
System.err.println("Usage: java Server <port number>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
Thread server = new KServer(port);
server.start();
//added waits just to make sure the thread was executed?
//thinking this might be my problem
long t = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < t) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
KClient client = new KClient("127.0.0.1",port);
while (!(client.openConn())) {
System.out.println("Failed to connect. Retrying...");
}
client.send("Hello World");
client.closeConn();
}
}
KServer.java
//the actual server class that manages listening and threading the sockets
import java.net.*;
import java.io.*;
public class KServer extends Thread {
private int port;
private ServerSocket sSock;
public KServer(int thisPort) {
port = thisPort;
try {
sSock = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while(true) {
try (Socket cSock = sSock.accept();) {
Thread con = new Connection(cSock);
con.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Connection.java
//Manages sending and receiving messages
import java.net.Socket;
import java.io.*;
public class Connection extends Thread {
Socket socket;
public Connection(Socket s) {
socket = s;
}
public void run() {
String msg;
BufferedReader in;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while((msg = in.readLine()) != null) {
System.out.println(msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
KClient.java
//manages the clients connection life to the server
import java.net.*;
import java.io.*;
public class KClient {
private Socket sock;
private String dest;
private int port;
private OutputStreamWriter out;
public KClient(String dst,int prt) {
dest = dst;
port = prt;
}
public boolean openConn() {
try {
sock = new Socket(dest,port);
out = new OutputStreamWriter(sock.getOutputStream(),"ISO-8859-1");
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public void send(String msg) {
try {
out.write(msg);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void closeConn() {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Don't use try-with-resources to accept the socket. It wil close the accepted socket, which needs to stay open so the handling thread can use it. The handling thread is responsible for closing it.

Java Sockets - EOFException when trying to implement multi-threading

I think it's because when I multi-thread the client&server, the DataOutputStream and DataInputStream buffers I use get overwritten or something like that since the socket can only have 1 duplex connection.
Here's what I have for now:
Client Class in my client program:
public static void main(String args[]) throws UnknownHostException, IOException, InterruptedException {
for (int i=0;i<2;i++) //change limit on i to change number of threads
{
new Thread(new ClientHandler(i)).start();
}
Thread.sleep(10000);
ClientHandler class in my client program:
(Sends a value to the server, the server will echo it back).
public class ClientHandler implements Runnable {
public int clientNumber;
public ClientHandler(int i){
this.clientNumber=i;
}
public void run() {
Socket socket = null;
try {
socket = new Socket("localhost",9990);
System.out.println("connected client number "+clientNumber);
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
DataInputStream input = new DataInputStream(socket.getInputStream());
output.writeDouble((new Random()).nextDouble());
System.out.println(input.readDouble());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
Server Class in my server program:
ServerSocket socket = new ServerSocket(9990);
try {
while (true) {
Socket threadSocket = socket.accept();
new Thread(new ServerHandler(threadSocket)).start();
Thread.sleep(10000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
socket.close();
}
}
}
ServerHandler Class in my server program (receives value from client and echoes it back)
public class ServerHandler implements Runnable {
private Socket socket;
public ServerHandler(Socket socket) {
this.socket = socket;
}
public void run() {
while(true) {
try {
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
double a = input.readDouble();
output.writeDouble(a);
}catch (IOException e){
e.printStackTrace();
}
}
}
So it's a pretty straight-forward implementation: create multiple threads of the client, and connect them to multiple threads of the server.
Everything works fine until the line:
double a = input.readDouble();
in my ServerHandler class.
I get an EOFException
I'm guessing it's because there can only be a single duplex connection between sockets. But if that's the case then how would I implement multi-threading of sockets at all?
So my question is: how can I get rid of the EOFException and allow myself to perform multi-threaded client-server socket interaction?
(preferably not changing much about my code because it's taken me a long time to get to this point).
The problem is that you share same Socket variable in ServerHandler for all threads:
private static Socket socket
Remove static keyword. Your ServerHandler will be something like this:
public static class ServerHandler implements Runnable {
private Socket socket;
public ServerHandler(Socket socket) {
this.socket = socket;
}
public void run() {
try {
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
double a = input.readDouble();
output.writeDouble(a);
} catch (IOException e) {
e.printStackTrace();
}
}
}

EOFException / SocketException when working with sockets and threads

This socket application works perfectly fine until I add support for multiple client connections to the server. Then I get a EOFException from the client, and a SocketException: Socket closed from the server.
Server.java:
public class Server {
static final int PORT = 8005;
static final int QUEUE = 50;
public Server() {
while (true) {
try (ServerSocket serverSocket = new ServerSocket(PORT, QUEUE);
Socket socket = serverSocket.accept();
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream())) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
output.writeUTF("Hey, this is the server!");
output.flush();
System.out.println(input.readUTF());
} catch (IOException e) {
System.out.println();
e.printStackTrace();
}
}
});
thread.start();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Server();
}
}
Client.java:
public class Client {
static final String HOST = "localhost";
static final int PORT = 8005;
public Client() {
try (Socket socket = new Socket(HOST, PORT);
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream())
) {
System.out.println(input.readUTF());
output.writeUTF("Hey, this is the client!");
output.flush();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static void main(String[] args) {
new Client();
}
}
A couple problems here:
You're creating a new ServerSocket for each pass through the loop. For a multi-client server you should instead be opening one ServerSocket and calling accept() on it for each client that connects.
Try-with-resources closes all resources it's provided with as soon as the try block is exited. You're creating a Thread that uses output but executes independently of the try block, so the execution flow is leaving the try block before thread finishes executing, resulting in socket (and output) being closed before the thread is able to use them. This is one of those situations where your resources need to be used outside the scope of the try block (in the thread you create to use them), so try-with-resources can't do all your resource handling for you.
I would rearrange your server code to something like:
public class Server {
static final int PORT = 8005;
static final int QUEUE = 50;
public Server() {
// create serverSocket once for all connections
try (ServerSocket serverSocket = new ServerSocket(PORT, QUEUE)) {
while (true) {
// accept a client connection, not in a try-with-resources so this will have to be explicitly closed
final Socket socket = serverSocket.accept();
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
// limit scope of input/output to where they're actually used
try (DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream())) {
output.writeUTF("Hey, this is the server!");
output.flush();
System.out.println(input.readUTF());
} catch (IOException e) {
System.out.println();
e.printStackTrace();
}
// implicitly close socket when done with it
try {
socket.close();
} catch (IOException e) {
System.out.println();
e.printStackTrace();
}
}
});
thread.start();
}
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static void main(String[] args) {
new Server();
}
}
Code is commented somewhat to explain some of the moves. Also note that the socket.close() call is in its own try-catch block to ensure that it's called even if the I/O streams throw an exception. It could equivalently (or perhaps more correctly now that I think about it) been placed in a finally block on the I/O stream try-catch block.

Why does the simple chat Server-Client always give me a BindException?

Why does the code below gives the following exception:
java.net.BindException: Address already in use: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:106)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:376)
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:190)
at java.net.ServerSocket.bind(ServerSocket.java:376)
at java.net.ServerSocket.<init>(ServerSocket.java:237)
at java.net.ServerSocket.<init>(ServerSocket.java:128)
at chap15.VerySimpleChatServer.go(VerySimpleChatServer.java:42)
at chap15.VerySimpleChatServer.main(VerySimpleChatServer.java:36)
I tried compiling it with netbeans. I created a project and put both classes inside it.
This is an example of the book "Head First Java", chapter 15
SERVER:
package chap15;
import java.io.*;
import java.net.*;
import java.util.*;
public class VerySimpleChatServer
{
ArrayList clientOutputStreams;
public class ClientHandler implements Runnable {
BufferedReader reader;
Socket sock;
public ClientHandler(Socket clientSOcket) {
try {
sock = clientSOcket;
InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(isReader);
} catch (Exception ex) { ex.printStackTrace(); }
}
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println("read " + message);
tellEveryone(message);
}
} catch (Exception ex) { ex.printStackTrace(); }
}
}
public static void main(String[] args) {
new VerySimpleChatServer().go();
}
public void go() {
clientOutputStreams = new ArrayList();
try {
ServerSocket serverSock = new ServerSocket(5000);
while(true) {
Socket clientSocket = serverSock.accept();
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("got a connection");
}
} catch (Exception ex) { ex.printStackTrace(); }
}
public void tellEveryone(String message) {
Iterator it = clientOutputStreams.iterator();
while (it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
} catch (Exception ex) { ex.printStackTrace(); }
}
}
}
The code "as posted in here" works.
You must have an old thread stuck or a process that is stuck somewhere. This happens if you were debugging it and didn't give it a chance to shut down properly.
Because something else is listening at the port, probably a prior instance of your own program that you haven't terminated yet. Or else you terminated it but there are still ports in TIME_WAIT state, which lasts for two minutes after the last inbound connection is closed.

Sending a message to all clients (Client - Server communication)

So now, I am making a client server app based multithread. In server side, I make a thread for everysingle connection that accepted.
In thread class, I make a method that send a command to client. What i just want is, how to send a parameter to all running client? For simple statement, i just want to make this server send a message to all connected client.
I've been read this post and find sendToAll(String message) method from this link. But when i am try in my code, there is no method like that in ServerSocket .
Okay this is my sample code for server and the thread.
class ServerOne{
ServerSocket server = null;
...
ServerOne(int port){
System.out.println("Starting server on port "+port);
try{
server = new ServerSocket(port);
System.out.println("Server started successfully and now waiting for client");
} catch (IOException e) {
System.out.println("Could not listen on port "+port);
System.exit(-1);
}
}
public void listenSocket(){
while(true){
ClientWorker w;
try{
w = new ClientWorker(server.accept());
Thread t = new Thread(w);
t.start();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
}
}
protected void finalize(){
try{
server.close();
} catch (IOException e) {
System.out.println("Could not close socket");
System.exit(-1);
}
}
}
class ClientWorker implements Runnable{
Socket client;
ClientWorker(Socket client){
this.client = client;
}
public void run(){
...
sendCommand(parameter);
...
}
public void sendCommand(String command){
PrintWriter out = null;
try {
out = new PrintWriter(client.getOutputStream(), true);
out.println(command);
} catch (IOException ex) {}
}
}
Thanks for help :)
The below answer, is not recommended for a full fledged server, as for this you should use Java EE with servlets, web services etc.
This is only intended where a few computers want to connect to perform a specific task, and using simple Java sockets is not a general problem. Think of distributed computing or multi-player gaming.
EDIT: I've - since first post - greatly updated this architecture, now tested and thread-safe. Anybody who needs it may download it here.
Simply use (directly, or by subclassing) Server and Client, start() them, and everything is ready. Read the inline comments for more powerful options.
While communication between clients are fairly complicated, I'll try to simplify it, the most possible.
Here are the points, in the server:
Keeping a list of connected clients.
Defining a thread, for server input.
Defining a queue of the received messages.
A thread polling from the queue, and work with it.
Some utility methods for sending messages.
And for the client:
Defining a thread, for client input.
Defining a queue of the received messages.
A thread polling from the queue, and work with it.
Here's the Server class:
public class Server {
private ArrayList<ConnectionToClient> clientList;
private LinkedBlockingQueue<Object> messages;
private ServerSocket serverSocket;
public Server(int port) {
clientList = new ArrayList<ConnectionToClient>();
messages = new LinkedBlockingQueue<Object>();
serverSocket = new ServerSocket(port);
Thread accept = new Thread() {
public void run(){
while(true){
try{
Socket s = serverSocket.accept();
clientList.add(new ConnectionToClient(s));
}
catch(IOException e){ e.printStackTrace(); }
}
}
};
accept.setDaemon(true);
accept.start();
Thread messageHandling = new Thread() {
public void run(){
while(true){
try{
Object message = messages.take();
// Do some handling here...
System.out.println("Message Received: " + message);
}
catch(InterruptedException e){ }
}
}
};
messageHandling.setDaemon(true);
messageHandling.start();
}
private class ConnectionToClient {
ObjectInputStream in;
ObjectOutputStream out;
Socket socket;
ConnectionToClient(Socket socket) throws IOException {
this.socket = socket;
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());
Thread read = new Thread(){
public void run(){
while(true){
try{
Object obj = in.readObject();
messages.put(obj);
}
catch(IOException e){ e.printStackTrace(); }
}
}
};
read.setDaemon(true); // terminate when main ends
read.start();
}
public void write(Object obj) {
try{
out.writeObject(obj);
}
catch(IOException e){ e.printStackTrace(); }
}
}
public void sendToOne(int index, Object message)throws IndexOutOfBoundsException {
clientList.get(index).write(message);
}
public void sendToAll(Object message){
for(ConnectionToClient client : clientList)
client.write(message);
}
}
And here for the Client class:
public class Client {
private ConnectionToServer server;
private LinkedBlockingQueue<Object> messages;
private Socket socket;
public Client(String IPAddress, int port) throws IOException{
socket = new Socket(IPAddress, port);
messages = new LinkedBlokingQueue<Object>();
server = new ConnecionToServer(socket);
Thread messageHandling = new Thread() {
public void run(){
while(true){
try{
Object message = messages.take();
// Do some handling here...
System.out.println("Message Received: " + message);
}
catch(InterruptedException e){ }
}
}
};
messageHandling.setDaemon(true);
messageHandling.start();
}
private class ConnectionToServer {
ObjectInputStream in;
ObjectOutputStream out;
Socket socket;
ConnectionToServer(Socket socket) throws IOException {
this.socket = socket;
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());
Thread read = new Thread(){
public void run(){
while(true){
try{
Object obj = in.readObject();
messages.put(obj);
}
catch(IOException e){ e.printStackTrace(); }
}
}
};
read.setDaemon(true);
read.start();
}
private void write(Object obj) {
try{
out.writeObject(obj);
}
catch(IOException e){ e.printStackTrace(); }
}
}
public void send(Object obj) {
server.write(obj);
}
}
There is no method in server socket to send data or message to all running clinet threads.
Please go through the ServerThread.java program which is calling the sendToAll usng server.
// ... and have the server send it to all clients
server.sendToAll( message );
Check out zeroMQ. There are methods known as "pub sub" or "publish subscribe" that will do what you want. You can also use it to communicate between your threads. It is an amazing library in my opinion. It has java or jzmq bindings along with over 30+ others as well so you should be able to use it in your program.
http://www.zeromq.org/

Categories

Resources