server doesn't receive data from multiple clients (java sockets) - java

I wrote a simple program where a server should print data sent by multiple clients. But the server receives only partial data. Following are the relevant pieces of the code.
Server:
try {
serverSocket = new ServerSocket(8888);
} catch (IOException e) {
System.err.println("Could not listen on port: 8888");
System.exit(-1);
}
while (listening) {
Socket clientSocket = serverSocket.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
System.out.println(reader.readLine());
reader.close();
clientSocket.close();
}
serverSocket.close();
Client:
try {
socket = new Socket("nimbus", 8888);
writer = new PrintWriter(socket.getOutputStream(), true);
localHost = InetAddress.getLocalHost();
}
catch (UnknownHostException e) {}
catch (IOException e) {}
StringBuilder msg1 = new StringBuilder("A: ");
for(int i=1; i<=3; i++)
msg1.append(i).append(' ');
writer.println(localHost.getHostName() + " - " + msg1);
StringBuilder msg2 = new StringBuilder("B: ");
for(int i=4; i<=6; i++)
msg2.append(i).append(' ');
writer.println(localHost.getHostName() + " - " + msg2);
StringBuilder msg3 = new StringBuilder("C: ");
for(int i=7; i<=9; i++)
msg3.append(i).append(' ');
writer.println(localHost.getHostName() + " - " + msg3);
writer.close();
socket.close();
I get the following output (when run on 3 clients)
nimbus2 - A: 1 2 3
nimbus3 - A: 1 2 3
nimbus4 - A: 1 2 3
I don't get the second and third messages. Server keeps waiting. Where am I going wrong?
Edit: In the server code, I tried removing reader.close() and clientSocket.close(). That didn't work either. Another question -- if 3 clients send 3 messages, does it require 9 connections? (this is the reason, I closed the connection in the server code)

You probably want to be delegating the handing of the socket to another thread. I've written up an example that works by passing each incoming socket to an Executor so it can read all the inputs. I use a Executors.newCachedThreadPool() which should grow to be as big as needed. You could also use Executors.newFixedThreadPool(1) if you want it to only be able to handle 1 client at a time.
The only other change I made was I removed the BufferedReader and replaced it with a Scanner. I was having issues with the BufferedReader not returning data. I'm not sure why.
Executor exe = Executors.newCachedThreadPool();
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8888);
} catch (IOException e) {
System.err.println("Could not listen on port: 8888");
System.exit(-1);
}
while (listening) {
final Socket clientSocket = serverSocket.accept();
exe.execute(new Runnable() {
#Override
public void run() {
try {
Scanner reader = new Scanner(clientSocket.getInputStream());
while(reader.hasNextLine()){
String line = reader.nextLine();
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
serverSocket.close();

It looks like you close the connection to the client before they can finish writing/before the server reads all of the messages they sent. I think you need to continue to readline, and potentially not terminate the client's connection after they send you one message.

John is right.
you close the client connection by calling clientsocket.close() after reading the message that is why you cannot get the other messages. you should call clientsocket.close() when you have received all the messages

Related

socket programming code not running forever

I have a 2 nodes that should always communicate with each other, but they don't seem to talk for more than 1 interaction. After successfully sending and receiving 1 message, they stop.
My code looks like this:
The initiator:
try {
Socket client = new Socket(ip, port);
OutputStream toNode = client.getOutputStream();
DataOutputStream out = new DataOutputStream(toNode);
out.writeUTF("Start:Message");
System.out.println("Sent data");
InputStream fromNode = client.getInputStream();
DataInputStream in = new DataInputStream(fromNode);
if(in.readUTF().equals("Return Message")) {
System.out.println("Received data");
out.writeUTF("Main:Message");
System.out.println("Sent data again");
}
else
System.out.println("Error");
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The responder:
while(true) {
Socket server;
try {
server = s.accept();
DataInputStream in = new DataInputStream(server.getInputStream());
String msg = in.readUTF();
String[] broken_msg = msg.split(":");
if(broken_msg.length > 0)
System.out.println("Looping");
String ret;
if (broken[0].equalsIgnoreCase("Start")) {
ret = "Return Message";
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF(ret);
}
else if (broken[0].equalsIgnoreCase("Main")) {
//Do Useful work
}
} catch (IOException e) {
e.printStackTrace();
}
}
My output looks like this:
Looping
and:
Sent data
Received data
Sent data again
You are looping around the accept() call, accepting new connections, but your actual I/O code only reads one message per connection. You need an inner loop around the readUTF() calls, handling the entire connection until EOFException is thrown. Normally all the I/O for a connection is handled in a separate thread.
In order for programs to do repetitive actions, you would generally use looping of some sort, including for loops, while loops and do-while loops. For something like this where you don't know how many times you'd need to communicate in advance, then you would need to use a while loop, not a for loop.
Having said that, you have no while loops whatsoever inside of your connection code... so without code that would allow continued communication, your program will stop, exactly as you've programmed it to do.
Solution: fix this. Put in while loops where continued communication is needed.

#Java/Android Socket failed to read message

I have trouble with the Java Sockets.
I need to connect a server and a client through the local network and as there can be more then two devices connected to the router the Client must find out the Address of the server.
The only way I know to solve this problem is to get the three first numbers of the clients IP(v4)-address and loop every of the 254 other possible IPs.
(I know that this way is very slow and may cause many problems. If you know an alternative, I will be glad).
Actually the client is an android smartphone so I can get the DHCP-Info.
The problem is, that the read command to check if a device is a server will last forever.
If you need some code, here it is!
code:
onCreate:
final WifiManager manager = (WifiManager) super.getSystemService(WIFI_SERVICE);
final DhcpInfo dhcp = manager.getDhcpInfo();
final String address = intToIp(dhcp.ipAddress);
String addresspart=address.substring(0, address.lastIndexOf('.')+1);
ArrayList<HashMap<String, String>> l = null;
Log.d("Keyboard","initiating search");
try {
l = new checkConnections().execute(addresspart).get();
} catch (InterruptedException e1) {
e1.printStackTrace();
} catch (ExecutionException e1) {
e1.printStackTrace();
}
checkConnections:
ArrayList<HashMap<String,String>> l=new ArrayList<HashMap<String,String>>();
for(int i=1;i<=255;i++){
try {
worksocket=new Socket(addresspart[0]+i,61927);
workout=new BufferedOutputStream(worksocket.getOutputStream());
workin=new BufferedInputStream(worksocket.getInputStream());
byte[] buffer=new byte[6];
workin.read(buffer);//at this point the app freezes until you stop the serverside program
String answer=new String(buffer,"UTF-8");
Log.i("Keyboard","Welcome Message: "+answer);
if(answer.equalsIgnoreCase("sdk on")){
HashMap<String,String> hm=new HashMap<String,String>();
hm.put("address",addresspart[0]+i);
l.add(hm);
workout.write(intToBytes(8));
workout.write("closing".getBytes("UTF-8"));
worksocket.close();
continue;
}
else{
Log.d("Keyboard","No SDK-Programm detected");
worksocket.close();
continue;
}
} catch (UnknownHostException e) {
Log.d("Keyboard",addresspart[0]+i+" doesn't exists");
continue;
} catch ( InterruptedIOException e){
Log.w("System.warn",e.getCause()+e.getLocalizedMessage());
Log.d("Keyboard","timeout");
continue;
} catch (IOException e) {
Log.d("Keyboard",addresspart[0]+i+" doesn't exists");
e.printStackTrace();
continue;
}
}
return l;
the server's code:
ServerSocket serverSocket = new ServerSocket(61927);
System.out.println("Socket initiated");
Socket client = serverSocket.accept();
BufferedInputStream in=new BufferedInputStream(client.getInputStream());
BufferedOutputStream out=new BufferedOutputStream(client.getOutputStream());
System.out.println("client found");
byte[] buffer=new byte[11];
out.write("sdk on".getBytes("UTF-8"));
in.read(buffer);
String s=new String(buffer,"UTF-8");
if(!s.equals("got info")){
System.out.println("No SDK Client");
client.close();
serverSocket.close();
new Main();
}
Uh, I think I should ping the Broadcast-IP and listen for answers instead...
Android's Linux runtime allows it to read from which IP an answer is coming.

file transfer between server and client input stream

I'm working on a java server-client based file transfer over socket project, I'll sum up the project shortly, I have text files related to server and client, server related text contains which ports are going to be opened and client text contains the IP and port to be connected on(server side is like 4444 and client side is like 4444 localhost) The file transfer on a single client is running pretty ok, now I'm working on second client connection and transfer, what I'm trying to do is; when a second client is run, it will read the first line of the text file (which is already in use by the first client), I thought a recursion will solve the problem but seems I couldn't figure out what I've done wrong, below are the code snippet from client side
boolean connected = false;
private void connection() {
while (!connected) {
try {
FileReader fr = new FileReader("c_input.txt");
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
String delims = "[ ]";
String[] elements = new String[8];
elements = line.split(delims);
serverPort = Integer.parseInt(elements[portIndex]);
hostIP = elements[ipIndex];
clientSocket = new Socket(hostIP, serverPort);
is = clientSocket.getInputStream();
if (is != null) {
connected = true;
System.out.println("connected to " + hostIP + " from port "
+ serverPort);
br.close();
fr.close();
} else {
System.out.println("The port " + serverPort
+ " is occupied, now trying another port.");
portIndex = portIndex + 2;
ipIndex = ipIndex + 2;
connection();
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
}
}
I used recursion there, because if a port is bound by another client it has to read another line from text file and split and retry connection with the new line's inputs.(in terms short the whole method will run again) But when it comes to running, the first client connects and when second one tries to connect from same port with client1 the code still gets in if loop instead of getting in else block (I get the message from the if check's println on the console and by the way is in the if check stands for InputStream) which means there is a stream coming from server, is this normal? if so how can I achieve the whole thing connection method does all over again if the port is bound by another client?

Simple Client-Server Application - Socket problems

I'm writing a simple client-server application using TCP Sockets . It works with the multi-threading principle to allow for several client connections to the same server.
I'm having some trouble figuring out some of the errors I get with the sockets, i'm fairly new in this environment as you will probably tell.
I'll show you the code I have, and the output i get from it, but basically the problem lies in the very connecting of the clients to the server, and I ran through all the code but still can't find what's wrong with it.
Server:
public static ArrayList<String> userList = new ArrayList<String>();
public static int index;
public static String date;
public static void main(String args[]) throws Exception {//inicio main
ServerSocket server = new ServerSocket(6500); //Create socket on port 6500
System.out.println ("Server started on port 6500");
while (true){ //Waiting for clients
System.out.println("Server waiting for client connections..");
Socket socket = null;
BufferedReader reader = new BufferedReader(new FileReader("C:\\UNIV\\Redes\\workspace\\Copy of Ex_4.3_Teste\\lists\\blacklist.txt"));
String line = null;
socket = server.accept();
// Blacklist verification
while ((line = reader.readLine()) != null) {
if (line.equals(socket.getInetAddress().toString())) {
System.out.println("IP Blacklisted: " + socket.getInetAddress().toString());
System.out.println("Closing connection to " + socket.getInetAddress().toString());
PrintStream checkBlack = new PrintStream(socket.getOutputStream(),true);
checkBlack.println("***BLACKLISTED***");
reader.close();
checkBlack.close();
socket.close();
break;
}
}//End of Blacklist Verification
//Sending feedback in case of approved client
try {
PrintStream checkBlack = new PrintStream(socket.getOutputStream(),true);
checkBlack.println("***NBLACKLISTED***");
checkBlack.close();
} catch (SocketException e) {
}
userList.add(socket.getInetAddress().toString()); //Add connected user's IP to USERLIST
System.out.println("New connection..");
System.out.println("Size of UserList: " + userList.size());
Thread t = new Thread(new EchoClientThread(socket));
t.start(); //Starting Client Thread
}//End of Waiting for Clients
}//End of Main
public static class EchoClientThread implements Runnable{
private Socket s;
public EchoClientThread(Socket socket) {
this.s = socket;
}
public void run() {
String threadName = Thread.currentThread().getName(); //Thread Name
String stringClient = s.getInetAddress().toString(); //Client IP
System.out.println("Connected to " + stringClient);
try{
BufferedReader input = new BufferedReader(
new InputStreamReader(s.getInputStream()));
PrintStream output = new PrintStream(
s.getOutputStream(),true);
String line;
while ((line = input.readLine()) !=null) { //Input Cycle
System.out.println (stringClient+": "+threadName+": "+line); //Print command from client
if (line.equalsIgnoreCase("9")){ //Exit
break;
}
else if (line.equalsIgnoreCase("1")){ //Send List of Online Users
System.out.println("Option 1: Sending list of online users to " + stringClient);
output.println(" ");
output.println("List of Online Users:");
output.println(" ");
for(int i=0;i<userList.size();i++){
output.println(userList.get(i));
}
}
else if (line.equalsIgnoreCase("2")) { //Send message to a single user
System.out.println("Nothing here yet..");
}
else if (line.equalsIgnoreCase("3")) { //Send message to all the online users
System.out.println("Nothing here yet..");
}
else if (line.equalsIgnoreCase("4")){ //Send User Blacklist
System.out.println("Option 4: Sending user blacklist to " + stringClient);
BufferedReader reader = new BufferedReader(new FileReader("C:\\UNIV\\Redes\\workspace\\Copy of Ex_4.3_Teste\\lists\\blacklist.txt"));
String lineRead = null;
output.println(" ");
output.println("User Blacklist:");
output.println(" ");
while ((lineRead = reader.readLine()) != null) {
output.println(lineRead);
}
reader.close();
}
else{
output.println("Unknown command.");
}
output.println("***CLOSE***"); //Closes client's input cycle
output.println("***NBLACKLISTED***"); //Sending feedback in case of approved client
}//Input Cycle End
output.println("See you later!");
input.close(); //Closes inputStream
output.close(); //Closes outputStream
s.close(); //Closes Socket
}
catch (Exception e){
System.err.println("Server Side Error!");
System.out.println(e);
}
userList.remove(s.getInetAddress().toString());
System.out.println("Client "+ stringClient+" was disconnected!");
}//End of run()
}//End of EchoClientThread
}//End of EchoServerThread
Client:
public static void main(String args[]) throws Exception {
if (args.length !=1){
System.err.println ("usage: java EchoClient2 <host>");
System.exit(1);
}
String host = args[0];
int port = 6500;
String cmd, line;
Socket socket = new Socket(host,port);
BufferedReader input = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
PrintStream output = new PrintStream(socket.getOutputStream(),true);
while( true ) {//Input cycle
Scanner scan = new Scanner (System.in);
if (input.readLine().equals("***BLACKLISTED***")) {
System.out.println("IP is Blacklisted");
break;
}
System.out.println(" ");
System.out.println("CLIENT MENU");
System.out.println(" ");
System.out.println("1 - List on-line users");
System.out.println("2 - Send message to a single user");
System.out.println("3 - Send message to all on-line users");
System.out.println("4 - List Blacklisted Users");
System.out.println("9 - Exit");
System.out.println(" ");
System.out.print(host+":"+port+"#>"); //Command prompt
cmd = scan.nextLine(); //Scanning command to send to the server
output.println(cmd); //Sending command to the server
if ( cmd.equalsIgnoreCase("9")){
System.out.println("Exiting..");
break;
}
try {
while (!(line = input.readLine()).equals("***CLOSE***")) { //Input Cycle
System.out.println (line); //Prints server answer
}
} catch (Exception e) {
System.err.println("Client Side Error!");
System.out.println(e);
break;
}
}//End of Cycle
System.out.println("Connection Terminated");
input.close(); //Closes inputStream
output.close(); //Closes outputStream
socket.close(); //Closes Socket
}
}
So the server starts fine with the following output:
Server started on port 6500
Server waiting for client connections..
But as soon as I try to connect with the client, this happens:
Server Side:
Server started on port 6500
Server waiting for client connections..
New connection..
Size of UserList: 1
Server waiting for client connections..
Connected to /127.0.0.1
java.net.SocketException: Socket is closed
Server Side Error!
Client /127.0.0.1 was disconnected!
On the client side, though, it still shows the input menu, and the command prompt, like so:
CLIENT MENU
1 - List on-line users
2 - Send message to a single user
3 - Send message to all on-line users
4 - List Blacklisted Users
9 - Exit
127.0.0.1:6500#>
And when I input something on the Client Side prompt, i get:
127.0.0.1:6500#>1
Client Side Error!
java.net.SocketException: Software caused connection abort: recv failed
Connection Terminated
I know what the errors mean, Socket is closed is pretty much self-explanatory, but i just can't find wheres the code problem that makes the socket close.
Any help is much appreciated.
You have your blacklist mechanism not quite right.
When you close a stream associated with the socket it will close the socket as well.
So the server is closing any socket that it gets and then hands it on to a thread,
which tries to use the socket and fails.
// Blacklist verification
while ((line = reader.readLine()) != null) {
// blah blah blah
}//End of Blacklist Verification
//Sending feedback in case of approved client
try {
PrintStream checkBlack = new PrintStream(socket.getOutputStream(),true);
checkBlack.println("***NBLACKLISTED***");
checkBlack.close(); // <== why are you closing the stream?
} catch (SocketException e) {
}
try this instead
// Blacklist verification
while ((line = reader.readLine()) != null) {
// blah blah blah
}//End of Blacklist Verification
//Sending feedback in case of approved client
try {
socket.getOutputStream().write("***NBLACKLISTED***\n".getBytes());
} catch (SocketException e) {
e.printStackTrace();
}
A debugger is your friend.

How to send commands and receive responses to OSGi console via a Java Socket?

I want to run OSGi framework on another computer (in a main method). So I wanted to know is there any way to connect to the OSGi console from the other computer and manage bundles?
I thought maybe using a java.net.Socket would help, and that's how I implemented that. I've used 2 threads. one for processing user input stream, and the other one that processes OSGi Console response. This is the first thread (processes user input stream):
configMap.put("osgi.console", "6666");
Framework fwk = ff.newFramework(configMap);
try {
fwk.start();
} catch (BundleException e) {
e.printStackTrace();
}
//__________________________________________________________________//
try {
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
Socket socket = new Socket(InetAddress.getByName("0.0.0.0"), 6666);
printlnInfo("Socket has been created: " + socket.getInetAddress() + ":" + socket.getPort());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
ConsoleOutputReciever fr = new ConsoleOutputReciever();
new Thread(fr).start();
while (true) {
String userInput = "";
while ((userInput = stdIn.readLine()) != null) {
System.out.println("--> " + userInput);
out.write(userInput + "\n");
out.flush();
}
System.out.println("2");
}
} catch (Exception e1) {
e1.printStackTrace();
}
This is the second thread (processes OSGi Console response):
public class ConsoleOutputReciever implements Runnable {
public Scanner in = null;
#Override
public void run() {
printlnInfo("ConsoleOutputReciever Started");
try {
Socket socket = new Socket(InetAddress.getByName("0.0.0.0"), 6666);
printlnInfo("Socket has been created: " + socket.getInetAddress() + ":" + socket.getPort());
String osgiResponse = "";
in = new Scanner(socket.getInputStream());
try {
while (true) {
in = new Scanner(socket.getInputStream());
while (in.hasNext()) {
System.out.println("-- READ LOOP");
osgiResponse = in.nextLine();
System.out.println("-- " + osgiResponse);
}
}
} catch (IllegalBlockingModeException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
but I only receive the first response of the OSGi console. like this:
--READ LOOP
--
--READ LOOP
ss
--> ss
Any ideas about the problem or any other way to connect to OSGi console remotely?
you are using blocking io, thus your inner while loop will never finish until the socket is closed. you need 2 threads to accomplish this with blocking io streams. 1 thread reads from stdin and writes to the socket output stream, the other thread reads from the socket input stream and writes to stdout.
also, you probably want to write a newline after sending the userInput to the osgi console (Scanner.nextLine() eats the newline).
lastly, you don't generally want to use the Print* classes when working with sockets as they hide IOExceptions.
Instead of building your own thing you might want to use one of the remote shells that are available, for example the Apache Felix one at http://felix.apache.org/site/apache-felix-remote-shell.html

Categories

Resources