Why multicasting isn't working? - java

My program doesn't work properly. The problem is that second client can't see messages from the first. I think problem is in while loop. Just not reading from IP adress. Can you help me?
Thank you in advance.
package multicastchat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
public class MulticastChat {
int chatRoom = 0;
int port = 0;
String ipAdress = "";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public MulticastChat(){
}
public void choosingChatRoom() throws IOException{
while (!(chatRoom > 0 && chatRoom < 5)) {
System.out.println(
"We have four chat rooms, choose one of them (1, 2, 3, 4)");
chatRoom = Integer.valueOf(br.readLine());
switch (chatRoom) {
case 1:
port = 4441;
ipAdress = "230.0.0.1";
break;
case 2:
port = 4442;
ipAdress = "230.0.0.2";
break;
case 3:
port = 4443;
ipAdress = "230.0.0.3";
break;
case 4:
port = 4444;
ipAdress = "230.0.0.4";
break;
default:
System.out.println("Sorry, but we haven't this room, try another room");
this.choosingChatRoom();
break;
}
System.out.println("Welcome to room " + chatRoom);
}
}
public static void main(String[] args) throws IOException {
MulticastChat mc = new MulticastChat();
mc.choosingChatRoom();
MulticastSocket socket = new MulticastSocket(mc.port);
InetAddress address = InetAddress.getByName(mc.ipAdress);
socket.joinGroup(address);
DatagramPacket outMessage;
DatagramPacket inMessage;
String userInput;
while (true) {
//Receiving message
inMessage = new DatagramPacket(new byte[4096], 4096);
inMessage.setLength(inMessage.getData().length);
socket.receive(inMessage);
String received = new String(
inMessage.getData(), 0, inMessage.getLength());
System.out.println(received);
//Sending message
if ((userInput = mc.br.readLine()) != null) {
if (userInput.equals("quit")) {
System.out.println("Bye, see you later ^_^");
socket.leaveGroup(address);
socket.close();
System.exit(0);
} else {
byte[] buff = userInput.getBytes();
outMessage =
new DatagramPacket(buff, buff.length, address, mc.port);
socket.send(outMessage);
}
}
}
}
}

Assuming you are using the same program at both ends of the chat nothing will happen. Each instance starts up by reading from the socket, before anything's been written, so it will block forever.
No instance ever gets to where it can write to the socket.
Note that socket programming usually requires several threads as things are happening asynchronously on at least two "channels" (user interaction and socket I/O). A full explanation of how to write networking code is far beyond what StackOverflow is designed for.

Related

Java Thread Bind Exception combined with address already in use error (client server using sockets)

There are two files (client file, server file) in this program that are supposed to be able to send and receive messages (utf-8 strings) to each other. Each file has a thread (one thread for client, one thread for server)
The client and the server connect on localhost with a port number (it should be the same port number when typing on the command prompt / mac terminal window)
However, the server is supposed to only send messages to all the other clients after receiving a message from a client. In other words, if a client sends a message to the server, the server cannot send that message back to the same client--it can only send messages to the different clients.
Another way to say it: Once a client is connected, it can send messages to the server. It will also receive from the server all messages sent from the other connected clients (not the messages sent from itself).
At runtime, there is supposed to be only one server (mac terminal / command prompt windows) but there can be multiple/infinite number of clients (mac terminal / command prompt windows)
Screenshot of error (server side):
Screenshot of error (client side):
Code of ChatServer.java:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ChatServer
{
private static Socket socket;
public static void main(String args[])
{
Thread ChatServer1 = new Thread ()
{
public void run ()
{
System.out.println("Server thread is now running");
try
{
int port_number1 = 0;
int numberOfClients = 0;
boolean KeepRunning = true;
if(args.length>0)
{
port_number1 = Integer.valueOf(args[0]);
}
System.out.println("Waiting for connections on port " + port_number1);
try
{
ServerSocket serverSocket = new ServerSocket(port_number1);
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println( "Listening for connections on port: " + ( port_number1 ) );
while(KeepRunning)
{
ServerSocket serverSocket = new ServerSocket(port_number1);
//create a list of clients
ArrayList<String> ListOfClients = new ArrayList<String>();
//connect to client
socket = serverSocket.accept();
//add new client to the list, is this the right way to add a new client? or should it be in a for loop or something?
ListOfClients.add("new client");
numberOfClients += 1;
System.out.println("A client has connected. Waiting for message...");
ListOfClients.add("new client" + numberOfClients);
//reading encoded utf-8 message from client, decoding from utf-8 format
String MessageFromClientEncodedUTF8 = "";
BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
String MessageFromClientDecodedFromUTF8 = BufReader1.readLine();
byte[] bytes = MessageFromClientEncodedUTF8.getBytes("UTF-8");
String MessageFromClientDecodedUTF8 = new String(bytes, "UTF-8");
//relaying message to every other client besides the one it was from
for (int i = 0; i < ListOfClients.size(); i++)
{
if(ListOfClients.get(i)!="new client")
{
String newmessage = null;
String returnMessage = newmessage;
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage + "\n");
System.out.println("Message sent to client: "+returnMessage);
bw.flush();
}
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (socket != null)
{
socket.close ();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
};
ChatServer1.start();
}
}
Code of ChatClient.java:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ChatClient
{
private static Socket Socket;
static int numberOfClients = 0;
public static void main(String args[])
{
//If I wanted to create multiple clients, would this code go here? OR should the new thread creation be outside the while(true) loop?
while (true)
{
String host = "localhost";
int numberOfClients = 0;
Thread ChatClient1 = new Thread ()
{
public void run()
{
try
{
//Client begins, gets port number, listens, connects, prints out messages from other clients
int port = 0;
int port_1number1 = 0;
int numberofmessages = 0;
String[] messagessentbyotherclients = null;
System.out.println("Try block begins..");
System.out.println("Chat client is running");
String port_number1= args[0];
System.out.println("Port number is: " + port_number1);
if(args.length>0)
{
port = Integer.valueOf(port_number1);
}
System.out.println("Listening for connections..");
System.out.println( "Listening on port: " + port_number1 );
Socket.connect(null);
System.out.println("Client has connected to the server");
for(int i = 0; i < numberOfClients; i++)
{
System.out.println(messagessentbyotherclients);
}
//client creates new message from standard input
OutputStream os = Socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input encoded in UTF-8 string format
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String line = "";
System.out.println( "Standard input (press enter then control D when finished): " );
while( (line= input.readLine()) != null )
{
newmessage += line + " ";
input=null;
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
//Sending the message to server
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
}
catch (IOException e)
{
e.printStackTrace();
}
}
};
ChatClient1.start();
}
}
}
These two errors have been covered many times and I've heard that the answer is to put the socket in a loop, which it already is in (while loop).
My question is: Is there a way to locate the errors before running it? Whenever I compile the program I don't get any errors in eclipse, but when I run it in the command prompt window / mac terminal, it does tell me that something is wrong. Or perhaps there's a line of code that I'm overlooking?
ServerSocket serverSocket = new ServerSocket(port_number1);
Place it once, before the while loop.

No response form Server Socket Java

Please help, connection to server has been made but the server willl not respond to any requests. Just trying to get the time and date working by sending the server "1". P.s i know i should not have all of the cases of 1-7 but i just want to get the date ad time working before worrying about any others
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Date;
import java.util.Scanner;
/**
*
* #author samdo
*/
public class SocketProgrammingSamD {
/**
* #param args the command line arguments
*/
private static Scanner in;
public static void main(String[] args) throws IOException {
System.out.println("Samuel Donini");
System.out.println(" ");
System.out.println("Project 1");
System.out.println(" ");
System.out.println(" ");
//new Driver().execute(args);//Creates an instance of the Driver class and Calls the Driver.execute method
in = new Scanner(System.in);
System.out.println("(Client) Enter Server Ip to Connect to(Empty will give localhost):");
String ip = in.nextLine();
System.out.println("(Client) Enter your server port no:");
int port = in.nextInt();
if (ip == null || ip.length() == 0) {
ip = "localhost";
}
System.out.println("Connecting to " + ip + ":" + port);
// for taking input from client
// InputStream inputStream = connectionSocket.getInputStream();
// Try to connect to port and the IP address given on the command line.
try (Socket socket = new Socket(ip, port)) {
// for taking input from client
// InputStream inputStream = connectionSocket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader inputFromClient = new BufferedReader(inputStreamReader);
// for giving output to the client.
OutputStream outputStream = socket.getOutputStream();
// output to client, to send data to the server
DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
// get output from server
InputStream serverInputStream = socket.getInputStream();
InputStreamReader inputStreamReaderFromServer = new InputStreamReader(
serverInputStream);
BufferedReader bufferReader = new BufferedReader(
inputStreamReaderFromServer);
//System.out.println("(Client) Give input:");
System.out.printf("Menu Options:\t\t\tCommands\n");
System.out.printf("-------------\t\t\t--------\n");
System.out.printf(" * 1 current Date & Time:\t1\n");
System.out.printf(" * 2 uptime: \t\t 2\n");
System.out.printf(" * 3 memory use: \t\t3\n");
System.out.printf(" * 4 Netstat: \t\t 4\n");
System.out.printf(" * 5 current users: \t\t5\n");
System.out.printf(" * 6 disk usage: \t\t6\n");
System.out.printf(" * 7 Quit: \t\t\t7\n\n");
String readingLineFromUser = inputFromClient.readLine();
// sending data to server
dataOutputStream.writeBytes(readingLineFromUser + "\n");
String getStringFromServer = bufferReader.readLine();
System.out.println("Got input from server (in client):" + getStringFromServer);
//attempts to get System Time
System.out.println("Requesting system time");
System.out.println("1");
//System.out.write("Server Date" + (new Date()).toString() + "\n");
System.out.println("Response from the server:\n");
// Read lines from the server and print them until "ServerDone" on
// a line by itself is encountered.
String answer;
while ((answer = inputFromClient.readLine()) != null && !answer.equals("ServerDone")) {
System.out.println(answer);
}
return;
}
}
}
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
public class Server {
private static ServerSocket severSocket;
private static Scanner in;
public static void main(String[] args) throws IOException {
in = new Scanner(System.in);
System.out.println("(Server) Enter your server port no:");
int port = in.nextInt();
System.out.println("Server Estabilsh Connection On Localhost or own ip with port : " + port);
severSocket = new ServerSocket(port);
System.out.println("Now you can run your client app.");
while (true) {
Socket connectionSocketListens = severSocket.accept();//Listens for a connection to be made to this socket and accepts it.
System.out.println("Accepted Client connection");
// for taking input from client
InputStream inputStream = connectionSocketListens.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader inputFromClient = new BufferedReader(
inputStreamReader);
// for giving output to the client.
OutputStream outputStream = connectionSocketListens.getOutputStream();
// output to client, to send data to the server
DataOutputStream dataOutputStream = new DataOutputStream(
outputStream);
// get output from server
String readingLineFromClientSocket = inputFromClient.readLine();
// sending data to client
String modified = doOperation(readingLineFromClientSocket);
// send data to client
dataOutputStream.writeBytes(modified + "\n");
// Read the request from the client! *** input = inputFromClient
String answer = inputFromClient.readLine();
System.out.println("Request from client "+answer);
Process cmdProc;
cmdProc = null;
// Execute the appropriate command.
if (answer.charAt(0) == '1') {
System.out.println("Responding to date and time request from the client ");
cmdProc = Runtime.getRuntime().exec("date");//MUST ADD TIME
}
if (answer.charAt(0) == '2') {
System.out.println("Responding to uptime request from the client ");
cmdProc = Runtime.getRuntime().exec("date");//MUST CHANGE
}
if (answer.charAt(0) == '3') {
System.out.println("Responding to memory use request from the client ");
cmdProc = Runtime.getRuntime().exec("date");
}
if (answer.charAt(0) == '4') {
System.out.println("Responding to Netstat request from the client ");
cmdProc = Runtime.getRuntime().exec("date");
}
if (answer.charAt(0) == '5') {
System.out.println("Responding to current users request from the client ");
cmdProc = Runtime.getRuntime().exec("date");
}
if (answer.charAt(0) == '6') {
System.out.println("Responding to disk usage request from the client ");
cmdProc = Runtime.getRuntime().exec("date");
}
if (answer.charAt(0) == '7') {
System.out.println("Responding to Quit request from the client ");
cmdProc = Runtime.getRuntime().exec("date");
}
else {
System.out.println("Unknown request ");
//need a socket.close or Server.close(); or something like that
return;
}
//Read the result of the commands and sent the result to the client one line at a time
// followed by the line "ServerDone"
BufferedReader cmdin = new BufferedReader(new InputStreamReader(cmdProc.getInputStream()));
String cmdans;
while ((cmdans = cmdin.readLine()) != null) {
System.out.println(cmdans);
}
System.out.println("ServerDone");
return;
}
}
private static String doOperation(String readingLineFromClientSocket) {
String[] array = readingLineFromClientSocket.split(" ");
StringBuilder strBuilder = new StringBuilder(array.length);
for (int i = array.length - 1; i >= 0; i--) {
String s = charReverse(array[i]);
strBuilder.append(s);
strBuilder.append(" ");
}
return strBuilder.toString();
}
private static String charReverse(String str) {
return new StringBuilder(str).reverse().toString();
}
}
I have a working version after making the following changes:
I changed this code in the Server class:
String answer = inputFromClient.readLine();
to
//String answer = inputFromClient.readLine();
String answer = modified;
System.out.println("Request from client "+answer);
Also all the lines like the following (apart from the first):
if (answer.charAt(0) == '2')
need to be
else if (answer.charAt(0) == '2')
and - on Windows at least - the following line:
cmdProc = Runtime.getRuntime().exec("date");
needs to be
cmdProc = Runtime.getRuntime().exec("cmd /c date /T");
This line:
while ((answer = inputFromClient.readLine()) != null && !answer.equals("ServerDone")) {
should be:
while ((answer = bufferReader.readLine()) != null && !answer.equals("ServerDone")) {
And after this line:
System.out.println(cmdans);
you need:
dataOutputStream.writeBytes(cmdans + "\n");

java IRC client file transfer

i'm stuck with a small problem that i can't solve .... i need to create an app in java that connects to irc server and have the ability to transfer a file to another client with in a specific channel. So i tried this below code and it doesnt work out,my problem is in making the socket to transfer the file. and at this given code i make the irc client to send you a file when you send a message "sendFile" to it, but it doesnt send the file named "any.txt" to the sender of the message. so what can i possibly do to transfer the file to the other client ??? .... and almost forgot ... when you try to send the command "sendFile" to the irc client, you must have a nickname "mer" without the "".
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.ServerSocket;
import java.io.File;
import java.io.FileInputStream;
import java.net.InetAddress;
public class MainTest {
private static String nickUse;
public static void main(String args[]) throws Exception{
// The server to connect to and our details.
File fileIn = new File("any.txt");
String server = "localhost";
String nick = "testJava";
String login = "anyName";
// The channel which the bot will join.
String channel = "#here";
// Connect directly to the IRC server.
ServerSocket serverSoc = new ServerSocket(0);
Socket socket = new Socket(server, 6667);
InetAddress intetAdd = socket.getInetAddress();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream( )));
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream( )));
// Log on to the server.
writer.write("NICK " + nick + "\r\n");
writer.write("USER " + login + " 8 * : This is a channel\r\n");
writer.flush( );
// Read lines from the server until it tells us we have connected.
String line = null;
while ((line = reader.readLine( )) != null) {
if (line.indexOf("004") >= 0) {
// We are now logged in.
break;
}
else if (line.indexOf("433") >= 0) {
System.out.println("Nickname is already in use.");
return;
}
}
// Join the channel.
writer.write("JOIN " + channel + "\r\n");
writer.flush( );
// Keep reading lines from the server.
while ((line = reader.readLine( )) != null) {
if (line.startsWith("PING ")) {
// We must respond to PINGs to avoid being disconnected.
writer.write("PONG " + line.substring(5) + "\r\n");
writer.flush();
System.out.println("THis is the line recieved when server sends a ping verification "+line);
}
else {
// Print the raw line received by the bot.
System.out.println(line);
if(line.contains(":") && line.contains("!")){
int positionOfIni = line.indexOf(":");
int lastOf = line.indexOf("!");
String nickComm = line.substring(positionOfIni+1,lastOf);
if(!nickComm.equalsIgnoreCase("mer")){
nickUse = nickComm;
}
}
if(nickUse!=null && line.endsWith(nickUse) == false){
int messagePo = line.lastIndexOf(":");
System.out.printf("%s %s %s\n",nickUse,"Says:",line.substring(messagePo+1));
nickUse = null;
}
if(line.endsWith("sendFile")){
byte[] add = intetAdd.getAddress();
writer.write("PRIVMSG " + "mer" +" :\u0001"+ "DCC SEND "+fileIn.getName()+" "+ipToLong(add)+" "+serverSoc.getLocalPort()+" "+fileIn.length()+"\u0001");
writer.flush();
Socket serSoc = serverSoc.accept();
serSoc.setSoTimeout(30000);
serverSoc.close();
BufferedOutputStream output = new BufferedOutputStream(serSoc.getOutputStream());
BufferedInputStream input = new BufferedInputStream(serSoc.getInputStream());
BufferedInputStream finput = new BufferedInputStream(new FileInputStream(fileIn));
byte[] outBuffer = new byte[1024];
byte[] inBuffer = new byte[4];
int bytesRead = 0;
while ((bytesRead = finput.read(outBuffer, 0, outBuffer.length)) != -1) {
output.write(outBuffer, 0, bytesRead);
output.flush();
input.read(inBuffer, 0, inBuffer.length);
Thread.sleep(4);
}
}
}
}
}
public static long ipToLong(byte[] address) {
if (address.length != 4) {
throw new IllegalArgumentException("byte array must be of length 4");
}
long ipNum = 0;
long multiplier = 1;
for (int i = 3; i >= 0; i--) {
int byteVal = (address[i] + 256) % 256;
ipNum += byteVal*multiplier;
multiplier *= 256;
}
System.out.println(ipNum);
return ipNum;
}
}
i just conclude the answer of having not to transfer with the help of IRC server. but instead i just create it's own server, that is capable of receiving files (Encrypted).

Java Server Basic Calculator

In this program, my server takes a command followed by 1 or 2 operands from the client and returns the result of the operation.
I am having trouble in scanning the line of client input and in performing the actual operation in the switch statement, if anyone could point me in the right direction I would appreciate it.
Here is the code:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
// Takes in a mathematical operation and the operands from a client and returns the result
// Valid operations are add, sub, multiply, power, divide, remainder, square
public class MathServer
{
public static void main(String [] args) throws IOException
{
ServerSocket yourSock = new ServerSocket(50000); //put server online
while(true)
{
System.out.println("Waiting to accept connection");
Socket clientSock = yourSock.accept(); //open server to connections
System.out.println("Connection accepted");
process(clientSock); //process accepted connection
System.out.println("Connection closed");
}
}
//BufferedReader(Reader r)
static void process(Socket sock) throws IOException
{
InputStream in = sock.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
OutputStream out = sock.getOutputStream();
PrintWriter pw = new PrintWriter(out, true);
String input = br.readLine(); //get user input from client
while(input != null && !input.equals("bye")) //check for input, if bye exit connection
{
int answer = operate(input); //perform desired operation on user input
pw.println(answer); //print out result
input = br.readLine(); //get next line of input
}
sock.close();
}
//Talk to the client
static int operate(String s)
{
System.out.println(s); //check if same as client input
Scanner myScanner = new Scanner(s);
String opType = myScanner.next(); //gets desired operation
System.out.println(opType); //checks for correct operation
switch (opType) {
case "add":
return (myScanner.nextInt() + myScanner.nextInt());
case "sub":
return (myScanner.nextInt() - myScanner.nextInt());
case "multiply":
return (myScanner.nextInt() * myScanner.nextInt());
case "power":
return (int) Math.pow(myScanner.nextInt(), myScanner.nextInt());
case "divide":
return myScanner.nextInt() / myScanner.nextInt();
case "remainder":
return myScanner.nextInt() % myScanner.nextInt();
case "square":
return (int) Math.pow(myScanner.nextInt(), 2);
default:
return (int) Math.pow(myScanner.nextInt(), 3);
}
}
}
As you're reading with BufferedReade.readLine() in your server, make sure you send a newline character from your client (common mistake). Also you may need to flush the OutputStream from your client. Because of the way that your Scanner reads in variables, you need to send in values on a single line from your client, e.g.
add 100 200
switch(opType) won't work for strings.
check with something like
if(opType.equals("add")){ //do Add }
else if(opType.equals("sub")){ //do subtraction }
etc.

How to return condition in a switch statement to while?

How to return action to while loop in a switch statement ? The client is unable to return to while statement. I meant to say, whenever response comes from server, the client must start from while loop again, so that client can select his choices. Is it a problem of System.out ? (Note: It's a copied code from others) Here are the client and server :
Client:
.............
while (true) {
String userchoice = console.readLine("Enter your choice :");
int choice= Integer.parseInt(userchoice);
switch (choice){
..........
case 2: // for viewing files in the client's directory
try{
Socket mysoc = new Socket("localhost", 9001);
String user_name = username;
DataOutputStream ToServer = new DataOutputStream(mysoc.getOutputStream());
ToServer.writeBytes(user_name + '\n');
BufferedReader FromServer = new BufferedReader(new InputStreamReader(mysoc.getInputStream()));
String line = null;
while ((line = FromServer.readLine()) != null) {
System.out.println(line);
}
}
catch(Exception e)
{
e.printStackTrace();
System.exit(0);
}
break;
............
}
Server:
import java.io.*;
import java.net.*;
class DirList
{
public static void main(String argv[]) throws Exception
{
String clientString;
//String replyString;
ServerSocket welcomeSoc = new ServerSocket(9001);
while(true)
{
Socket connectionSocket = welcomeSoc.accept();
BufferedReader FromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
PrintWriter ToClient = new PrintWriter(connectionSocket.getOutputStream(),true);
clientString = FromClient.readLine();
System.out.println("Received view songs request from : " + clientString);
String path = "/home/sri/Songs/";
String text="";
File f = new File(path);
File[] listOfFiles = f.listFiles();
for (int j = 0; j < listOfFiles.length; j++) {
if (listOfFiles[j].isFile()) {
text = listOfFiles[j].getName();
ToClient.println(text);
}
}
}
}
}
Why don't you label the outermost while like this..
outer: while(true)
and use the continue keyword to return to the label.
continue outer;
try to close your PrintWriter and Socket in the Server code after they finished their task.
#Sri, about the question you've asked in the comment:
by Socket I meant connectionSocket. ServerSocket will remain there during your server life time. But you will have a new connectionSocket for each user. so each connectionSocket will serve only a single client.

Categories