Please with multithreading in Java - java

I am a new java programmer and I have a file sharing program which I am trying to make it work continuously in a while(true) loop in a multithread. I have the sever running correctly but I can make the client to run continuously e.g. server establishes connection then I run client but I have to manually run it because after a file is transfer, client stops. Bellow is the code, can you please help me correct the error?
import java.net.*;
import java.io.*;
public class TCPServer
{
private static ServerSocket myServer;
private static Socket myClient = null;
public static void main(String[] args) throws IOException
{
try
{
myServer = new ServerSocket(6789);
System.out.println("Server is now available...");
}
catch(Exception e)
{
System.err.println("This port is unavailable.");
System.exit(1);
}
while(true)
{
try
{
myClient = myServer.accept();
System.out.println("Connection established to : " + myClient);
Thread t = new Thread(new ConnectionThread(myClient));
t.start();
}catch(Exception e)
{
System.err.println("Connection failed...!");
}
}
}
}
import java.net.*;
import java.io.*;
public class TCPClient
{
private static BufferedReader myReader;
private static PrintStream myOut;
private static String fileName;
private static Socket mySocket;
public static void main(String[] args) throws IOException
{
try
{
mySocket = new Socket("localhost", 6789);
myReader = new BufferedReader(new InputStreamReader(System.in));
}
catch(Exception e)
{
System.err.println("Couldn't establish a connection with server.");
System.exit(1);
}
try
{
myOut = new PrintStream(mySocket.getOutputStream());
switch (Integer.parseInt(sendOrReceive()))
{
case 1:
myOut.println("1");
sendFile();
break;
case 2:
myOut.println("2");
System.err.print("Enter file name: ");
fileName = myReader.readLine();
myOut.println(fileName);
receiveFile(fileName);
break;
}
mySocket.close();
}
catch(Exception e)
{
System.err.println("not valid input");
}
}
public static String sendOrReceive() throws IOException
{
System.out.println("1. Send file.");
System.out.println("2. Recieve file.");
System.out.print("\nMake selection: ");
return myReader.readLine();
}
public static void sendFile()
{
try
{
System.err.print("Enter file name: ");
fileName = myReader.readLine();
File myFile = new File("F:/" + fileName);
byte[] myArray = new byte[(int) myFile.length()];
FileInputStream myInFileStream = new FileInputStream(myFile);
BufferedInputStream myBufferStream = new BufferedInputStream(myInFileStream);
DataInputStream myDataIn = new DataInputStream(myBufferStream);
myDataIn.readFully(myArray, 0, myArray.length);
OutputStream myOutStream = mySocket.getOutputStream();
//Sending file name and file size to the server
DataOutputStream myDataOut = new DataOutputStream(myOutStream);
myDataOut.writeUTF(myFile.getName());
myDataOut.writeLong(myArray.length);
myDataOut.write(myArray, 0, myArray.length);
myDataOut.flush();
System.out.println("The file " + fileName + " was sent to the server.");
}
catch (Exception e)
{
System.err.println("The file " + fileName + " was not found!");
}
}
public static void receiveFile(String fileName)
{
try
{
InputStream myIn = mySocket.getInputStream();
DataInputStream myDataOut = new DataInputStream(myIn);
fileName = myDataOut.readUTF();
OutputStream myOut = new FileOutputStream(("F:/" + fileName));
long file = myDataOut.readLong();
byte[] buffer = new byte[1024];
int num = 0;
while (file > 0 && num != -1)
{
num = myDataOut.read(buffer, 0, (int) Math.min(buffer.length, file));
myOut.write(buffer, 0, num);
file -= num;
}
myOut.close();
myIn.close();
myDataOut.close();
System.out.println("The file " + fileName + " was received from the server.");
}
catch(IOException ex)
{
System.err.println("Connection closed.");
}
}
}
public class ConnectionThread implements Runnable
{
private Socket clientSocket;
private BufferedReader myBuffer = null;
public ConnectionThread(Socket aSocket)
{
this.clientSocket = aSocket;
}
#Override
public void run()
{
try
{
myBuffer = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String choice = "";
while((choice = myBuffer.readLine()) != null)
{
switch (choice)
{
case "1":
receiveFile();
break;
case "2":
String fileName;
while ((fileName = myBuffer.readLine()) != null)
{
sendFile(fileName);
}
break;
default:
System.out.println("Not a valid choice. Choice must be '1' or '2'.");
break;
}
myBuffer.close();
clientSocket.close();
break;
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void receiveFile()
{
try
{
DataInputStream myDataOut = new DataInputStream(clientSocket.getInputStream());
String fileName = myDataOut.readUTF();
FileOutputStream myOut = new FileOutputStream(("C:/SHARED/" + fileName));
long file = myDataOut.readLong();
byte[] buffer = new byte[1024];
int num = 0;
while (file > 0 && num != -1)
{
num = myDataOut.read(buffer, 0, (int) Math.min(buffer.length, file));
myOut.write(buffer, 0, num);
file -= num;
}
myOut.close();
myDataOut.close();
System.out.println("The file " + fileName + " was received from the client.");
}catch (IOException e)
{
System.err.println("Connection closed.");
}
}
public void sendFile(String fileName)
{
try
{
//handle file read
File myFile = new File("C:/Users/" + fileName);
byte[] myArray = new byte[(int) myFile.length()];
FileInputStream myInFileStream = new FileInputStream(myFile);
BufferedInputStream myInBufferStream = new BufferedInputStream(myInFileStream);
DataInputStream myDataIn = new DataInputStream(myInBufferStream);
myDataIn.readFully(myArray, 0, myArray.length);
//handle file send over socket
OutputStream myOutStream = clientSocket.getOutputStream();
//Sending file name and file size to the server
DataOutputStream myDataOut = new DataOutputStream(myOutStream);
myDataOut.writeUTF(myFile.getName());
myDataOut.writeLong(myArray.length);
myDataOut.write(myArray, 0, myArray.length);
myDataOut.flush();
System.out.println("The file " + fileName + " was sent to the client.");
}
catch(Exception e)
{
System.err.println("The file " + fileName + " was not found!");
}
}
}

I think you can just add a loop to your client's main, as Saket already said in a comment:
public static void main(String[] args) throws IOException
{
while(true) {
try
{
mySocket = new Socket("localhost", 6789);
myReader = new BufferedReader(new InputStreamReader(System.in));
}
...
...
}
}
You could add an option '3' to end the loop and client program:
case 3:
System.exit(0);
Threads would be needed if you wanted to download more than one file at a time with a single client.

Your code is hard to read but key problem is:
ConnectionThread
#Override
public void run()
{
try
{
...
}
}
you should try add while(true) below try:
#Override
public void run()
{
try
{
while(true) {
myBuffer = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String choice = "";
while((choice = myBuffer.readLine()) != null)
....
// remove close client connection
}
}
catch(Exception e)
{
System.err.println("The file " + fileName + " was not found!");
}
}
}

#mambo: In TCPClient, do not close connection, using while(true)
public class TCPClient
public static void main(String[] args) throws IOException
try
{
mySocket = new Socket("localhost", 6789);
myReader = new BufferedReader(new InputStreamReader(System.in));
}
catch(Exception e)
{
System.err.println("Couldn't establish a connection with server.");
System.exit(1);
}
while(true) {
.....
}

There are problems at 2 classes:
in TCPClient
myOut = new PrintStream(mySocket.getOutputStream());
switch (Integer.parseInt(sendOrReceive()))
{
case 1:
myOut.println("1");
sendFile();
break;
case 2:
myOut.println("2");
System.err.print("Enter file name: ");
fileName = myReader.readLine();
myOut.println(fileName);
receiveFile(fileName);
break;
}
mySocket.close();
The switch block work for only one choice, and later on mySocket will close.
In ConnectionThread Class
in while loop,
myBuffer.close();
clientSocket.close();
break;
Here clientSocket will close in first attempt only. It should be outside of while.

Related

How to access a string called "numberPart" from a different file (multithreaded java socket programming)

There is a string called numberPart inside a thread class called ServerRecieve. The location where .start() is being called is inside of a different class called Server.
The 'numberPart' will eventually be used as a port for file transferring later on.
My question is: How do I access the numberPart variable inside of the class called Server?
Screenshot of code running (server on left window, client on the right):
server on left window, client on the right
In the left window of the screenshot (server) you can see the that the first port number of the right window's command line argument which is 4021 being sent via a text message, and the server successfully receives it with the message "File transfer port found: 4021". Unfortunately this variable is located inside a different class. I would like to know how to access that variable inside the class called Server.
ServerRecieve code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class ServerRecieve extends Thread
{
Socket servSocket;
boolean m_bRunThread = true;
boolean ServerOn = true;
public ServerRecieve(Socket s)
{
super();
servSocket = s;
}
public void run()
{
while(true)
{
try
{
BufferedReader readFromClient = new BufferedReader(new InputStreamReader(servSocket.getInputStream()));
String fromClient = readFromClient.readLine();
String a = fromClient;
int i;
for(i = 0; i < a.length(); i++)
{
char c = a.charAt(i);
if( '0' <= c && c <= '9' )
{
break;
}
}
String alphaPart = a.substring(0, i);
String numberPart = a.substring(i);
System.out.println("Recieved from client: " + alphaPart +"\n");
System.out.println("File transfer port found: " + numberPart + "\n");
//String[] filePortNumber = null;
//filePortNumber[0] = numberPart;
// Server thing = new Server(filePortNumber);
if(fromClient.equals(null))
{
System.exit(0);
}
OutputOptions();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
}
void OutputOptions()
{
System.out.println("Enter an option ('m', 'f', 'x'): ");
System.out.println("(M)essage (send)");
System.out.println("(F)ile (request) ");
System.out.println("e(X)it ");
}
}
Server source:
import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.IIOException;
public class Server
{
private String[] serverArgs;
public Socket socket;
public Socket fileSocket;
public boolean keepRunning = true;
public int ConnectOnce = 0;
public String option = "";
public boolean isConnected = false;
public String FILE_TO_SEND = "/Users/nanettegormley/Documents/workspace/assignment2/src/servers/cdm.jpg";
public Server(String[] args) throws IOException
{
// set the instance variable
this.serverArgs = args;
if(ConnectOnce == 0)
{
int port_number1 = Integer.valueOf(serverArgs[1]);
ServerSocket serverSocket = new ServerSocket(port_number1);
socket = serverSocket.accept();
ConnectOnce = 4;
isConnected = true;
}
}
public String[] serverRun2(String[] args) throws IOException
{
serverArgs = args;
serverArgs = Arrays.copyOf(args, args.length);
serverSend.start();
return serverArgs;
}
Thread serverSend = new Thread()
{
public void run()
{
OutputOptions();
while(isConnected)
{
try
{
ServerRecieve serverThread = new ServerRecieve(socket);
serverThread.start();
// input the message from standard input
BufferedReader input2= new BufferedReader(new InputStreamReader(System.in));
option = input2.readLine();
if(option.equals("m") || option.equals("M"))
{
StandardOutput();
}
if(option.equals("f") || option.equals("F"))
{
FileTransferSend();
}
if(option.equals("x") || option.equals("X"))
{
System.exit(0);
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
}
}
};
public void StandardOutput()
{
try
{
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
System.out.println("Enter your message: ");
// input the message from standard input
BufferedReader input2= new BufferedReader(new InputStreamReader(System.in));
String line = "";
line= input2.readLine();
newmessage += line + " ";
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.newLine();
bw.flush();
System.out.println("Message sent to client: "+sendMessage);
StandardInput();
//run();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
void FileTransferSend()
{
//connect to the filetransfer
try
{
System.out.println("Which file do you want? ");
Scanner scanner = new Scanner(System.in);
String filename = scanner.nextLine();
FileInputStream fis = new FileInputStream(new File(filename));
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(fileSocket.getOutputStream()));
int element;
while((element = fis.read()) !=1)
{
dos.write(element);
}
byte[] byteBuffer = new byte[1024]; // buffer
while(fis.read(byteBuffer)!= -1)
{
dos.write(byteBuffer);
}
OutputOptions();
// dos.close();
// fis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
void OutputOptions()
{
System.out.println("Enter an option ('m', 'f', 'x'): ");
System.out.println("(M)essage (send)");
System.out.println("(F)ile (request) ");
System.out.println("e(X)it ");
}
public void StandardInput()
{
OutputOptions();
while(true)
{
try
{
// input the message from standard input
BufferedReader input2= new BufferedReader(new InputStreamReader(System.in));
String line2 = "";
option= input2.readLine();
if(option.equals("m") || option.equals("M"))
{
StandardOutput();
}
if(option.equals("f") || option.equals("F"))
{
FileTransferSend();
}
if(option.equals("x") || option.equals("X"))
{
System.exit(0);
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
finally
{
}
}
}
}
Full code with all files:
https://www.dropbox.com/s/0yq47gapsd3dgjp/folder33.zip?dl=0
My question is: What changes can I make to the code that would allow me to access numberPart while being inside Server?
EDIT: Is there a way to bump a question that hasn't gotten any answers or should I just delete this one and repost it somewhere?
I would think that you could use either a listener or callback pattern to solve this.
(I'm losing my Java memory now that I'm doing C# so please bear with me..)
interface PortAssignable {
public assignPort(int port);
}
Then have the Server class implement that interface
public Server implements PortAssignable {
...
}
And ServerReceive
// Constructor
public ServerRecieve(Socket s, PortAssignable portNotifyListener) {
_portNotifyListener = portNotifyListener;
... your other code ...
}
Make sure when you create an instance of ServerReceive, you pass in your Server instance, via this.
ServerRecieve serverThread = new ServerRecieve(socket, this);
Now, when you get your numberPart, your next line can be
_portNotifyListener.assignPort(numberPart);
How you choose to implement the assignPort method in your Server class is up to you.
P.S. I saw this question from /r/programming.

Multiple file chunks transfer over socket to multiple clients

I have to transfer chunks of a file to different clients using one server.
When i run the server file and provide the name of the file it successfully makes chunks. when i run the first client for first time it works but when i run it for the client again(by that i mean when i connect as a second client) it fails to transfer chunks to the second client. Complete code of server and client are shown below.
error is for the second client it starts reading the contents of the file as filename and program terminates.
provide a large text file(1MB) file as input to server
Server Code:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
public class server {
private static final int sPort = 8000; //The server will be listening on this port number
public static String str;
public static int c;
public static void main(String[] args) throws Exception {
System.out.println("The server is running.");
ServerSocket listener = new ServerSocket(sPort);
int clientNum = 1;
System.out.println("Enter the name of the file: ");
Scanner in = new Scanner(System.in);
str = in.nextLine();
String path = System.getProperty("user.dir");
String filepath = path +"/"+ str;
in.close();
try {
c=splitFile(new File(filepath));
} catch (IOException e1) {
e1.printStackTrace();
}
try {
while(true) {
new Handler(listener.accept(),clientNum,c).start();
System.out.println("Client " + clientNum + " is connected!");
clientNum++;
}
} finally {
listener.close();
}
}
/**
* A handler thread class. Handlers are spawned from the listening
* loop and are responsible for dealing with a single client's requests.
*/
private static class Handler extends Thread {
private Socket connection;
private int chunkcount;
private ObjectInputStream in; //stream read from the socket
private ObjectOutputStream out; //stream write to the socket
private int no; //The index number of the client
public Handler(Socket connection, int no,int c) {
this.connection = connection;
this.no = no;
this.chunkcount=c;
}
public void run() {
try{
//initialize Input and Output streams
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connection.getInputStream());
try{
String path = System.getProperty("user.dir");
path=path+"/"+"chunks"+ "/";
System.out.println(path);
System.out.println("Total chunks: "+chunkcount);
int i=no;
int j=i;
int k=0;
OutputStream op=connection.getOutputStream();
DataOutputStream d = new DataOutputStream(op);
d.writeInt(no);
d.flush();
System.out.println("value of j or clientnum: "+j);
while(j<chunkcount)
{
k++;
j=j+5;
}
System.out.println(k);
d.writeInt(k);
d.flush();
//d.close();
while(i<chunkcount)
{
String pathname= path+Integer.toString(i)+str;
System.out.println(i+str);
sendFile(connection,pathname);
i=i+5;
}
}
catch(Exception e){
e.printStackTrace();
}
}
catch(IOException ioException){
System.out.println("Disconnect with Client " + no);
}
finally{
//Close connections
try{
in.close();
out.close();
connection.close();
}
catch(IOException ioException){
System.out.println("Disconnect with Client " + no);
}
}
}
}
public static int splitFile(File f) throws IOException {
int partCounter = 1;//I like to name parts from 001, 002, 003, ...
//you can change it to 0 if you want 000, 001, ...
int sizeOfFiles = 102400;// 1MB
byte[] buffer = new byte[sizeOfFiles];
try (BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(f))) {//try-with-resources to ensure closing stream
String name = f.getName();
String path = f.getParent();
long sizefile = f.getTotalSpace();
String newpath = path + "/" + "chunks";
File dir = new File(newpath);
dir.mkdir();
int tmp = 0;
while ((tmp = bis.read(buffer)) > 0) {
//write each chunk of data into separate file with different number in name
File newFile = new File(dir, String.format("%d", partCounter++) + name );
//System.out.println(f.getParent());
try (FileOutputStream out = new FileOutputStream(newFile)) {
out.write(buffer, 0, tmp);//tmp is chunk size
}
}
System.out.println("File details are : "+name+" "+sizefile);
System.out.println("Number of chunks: "+ (partCounter-1));
}
return (partCounter-1);
}
public static void sendFile(Socket conn,String fileName) throws IOException
{
File myFile = new File(fileName);
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(mybytearray, 0, mybytearray.length);
OutputStream os = conn.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
dos.write(mybytearray, 0, mybytearray.length);
dos.flush();
dis.close();
}
}
client code:
import java.net.*;
import java.io.*;
public class Client {
Socket requestSocket; //socket connect to the server
ObjectOutputStream out; //stream write to the socket
ObjectInputStream in; //stream read from the socket
public Client() {}
void run()
{
try{
//create a socket to connect to the server
requestSocket = new Socket("localhost", 8000);
System.out.println("Connected to localhost in port 8000");
//initialize inputStream and outputStream
out = new ObjectOutputStream(requestSocket.getOutputStream());
out.flush();
in = new ObjectInputStream(requestSocket.getInputStream());
System.out.println("Ready to receive files ( Enter QUIT to end):");
BufferedInputStream in1 = new BufferedInputStream(requestSocket.getInputStream());
DataInputStream d = new DataInputStream(in1);
int clientnum=d.readInt();
String path = System.getProperty("user.dir");
String oppath = path + "/" + "Client" + clientnum;
File dir = new File(oppath);
dir.mkdir();
int numchunk=d.readInt();
System.out.println(numchunk);
int jakarta=1;
while(jakarta<=numchunk ){
jakarta++;
String newpath=oppath+"/";
File f = new File(newpath);
f.createNewFile();
receiveFile(requestSocket,newpath);
System.out.println("File Received");
}
}
catch (ConnectException e) {
System.err.println("Connection refused. You need to initiate a server first.");
}
catch(UnknownHostException unknownHost){
System.err.println("You are trying to connect to an unknown host!");
}
catch(IOException ioException){
ioException.printStackTrace();
}
finally{
//Close connections
try{
in.close();
out.close();
requestSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}
//send a message to the output stream
public static void receiveFile(Socket s1,String oppath) throws IOException
{
String fileName;
try {
int bytesRead;
InputStream in = s1.getInputStream();
DataInputStream clientData = new DataInputStream(in);
fileName = clientData.readUTF();
OutputStream output = new FileOutputStream(oppath+fileName);
long size = clientData.readLong();
byte[] buffer = new byte[1024];
while (size > 0
&& (bytesRead = clientData.read(buffer, 0,
(int) Math.min(buffer.length, size))) != -1) {
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
output.flush();
output.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
//main method
public static void main(String args[])
{
Client client = new Client();
client.run();
}
}

br.readline() gets stuck while br.read() works

I am making a simple ftp client/server program which on command from the clients lists files, tells the current directory, downloads files
My client code works fine since i have already tested it with a working server. However the server that i have designed gets stuck in the run() function on the line String message = br.readline(); If instead i use the br.read(), then it works but i need command in form of a string to know which file i have to download whereas br.read() returns int. Here's my code, i have used threading.
public class Myserver {
static final int PortNumber = 108;
static ServerSocket MyService;
static Socket clientSocket = null;
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
File directory;
directory = new File(System.getProperty("user.home"));
try {
MyService = new ServerSocket(PortNumber);
String cd = directory.toString();
System.out.println(cd);
System.out.println("Listening on " + PortNumber);
while(true) {
clientSocket = MyService.accept();
Connecthandle a = new Connecthandle(clientSocket, directory);
a.run();
}
}
catch (IOException e) {
System.out.println(e);
}
}
static class Connecthandle extends Thread {
File Directory;
Socket clientsocket;
// Constructor for class
Connecthandle(Socket clients, File dir) {
clientsocket = clients;
Directory = dir;
}
// Works Fine
void listfiles() throws IOException {
String []Listfile = Directory.list();
String send = "";
for (int j = 0; j < Listfile.length; j++) {
send = send + Listfile[j] + ",";
}
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(send);
GoingOut.flush();
GoingOut.close();
}
// Works Fine
void currentdirectory() throws IOException {
String cd = Directory.toString();
String cdd = "resp," + cd;
System.out.println(cdd);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(cdd);
GoingOut.flush();
GoingOut.close();
System.exit(0);
}
void sendfiles(String fileName) {
try {
File nfile = new File(fileName);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
if ( (! nfile.exists()) || nfile.isDirectory() ) {
GoingOut.writeBytes("file not present");
} else {
BufferedReader br = new BufferedReader(new FileReader(nfile));
String line;
while ((line = br.readLine()) != null) {
line = br.readLine();
GoingOut.writeBytes(line+"\n");
}
GoingOut.flush();
GoingOut.close();
br.close();
}
} catch (IOException e) {
System.out.println("Unable to send!");
}
}
#SuppressWarnings("deprecation")
public void run() {
try {
DataInputStream comingin = new DataInputStream(clientsocket.getInputStream());
InputStreamReader isr = new InputStreamReader(comingin, "UTF-8");
BufferedReader br = new BufferedReader(isr);
System.out.println("here");
// if (br.ready())
String message = br.readLine(); // Code gets stuck here, if i use br.read() it works, but i need string output.
if (message.equals("listfiles\n")) {
listfiles();
} else if (message.equals("pwd")) {
currentdirectory();
} else if (message.contains("getfile,")) {
String fileName = new String(message.substring(8, message.length()));
sendfiles(fileName);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
clientsocket.close();
} catch (IOException e) {}
}
}
}
}
If readLine() is blocking and you are sending data, you aren't sending a newline.

spawn another port on localhost FTP server to handle data

The programming is to emulate FTP server and client on localhost. The server should listen client's command on port 22222, and create another connection on port 22223 to transmit the data. I have achieved the trasmisstion on the same port which is 22222. The question is how actually to sparate one connection for receiving command: "get", "put" and create another connection on different port to transmit data? Can somebody please help me?
FTPServer.class
public class FTPServer {
public static void main(String args[]) throws Exception
{
int PORT =22222;
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("FTP Server Listening on Port " + PORT);
ExecutorService executor = Executors.newFixedThreadPool(10);
while(true)
{
System.out.println("Server is waiting...");
FileTransfer ft = new FileTransfer(serverSocket.accept());
executor.execute(ft);
}
}
}
class FileTransfer extends Thread
{
Socket clientSocket;
DataInputStream inFromClient;
DataOutputStream outToClient;
String filePath = "E:" +File.separator+"Studying"+
File.separator+"WorkSpace"+File.separator+"FTPServer"+File.separator;
FileTransfer(Socket socket)
{
try
{
clientSocket=socket;
inFromClient = new DataInputStream(clientSocket.getInputStream());
outToClient = new DataOutputStream(clientSocket.getOutputStream());
}catch(Exception ex){}
}
public void ClientDownLoad() throws Exception
{
String fileName = inFromClient.readUTF();
String accessfile = filePath + fileName;
File file = new File(accessfile);
if(!file.exists())
{
outToClient.writeUTF("FILE NOT FOUND");
return;
}
else
{
outToClient.writeUTF("Ready for download");
FileInputStream f = new FileInputStream(file);
int numOfByte;
do
{
numOfByte = f.read();
outToClient.writeUTF(String.valueOf(numOfByte));
}while(numOfByte!=-1);
f.close();
outToClient.writeUTF("Download Completed");
}
}
public void ClientUpLoad() throws Exception
{
String fileName = inFromClient.readUTF();
String userChoose;
String accessFile = filePath + fileName;
File file=new File(accessFile);
if(fileName.equalsIgnoreCase("No such file"))
{
return;
}
if(file.exists())
{
outToClient.writeUTF("File Exists in Server");
userChoose=inFromClient.readUTF();
}
else
{
outToClient.writeUTF("OK...You can send file");
userChoose="y";
}
if(userChoose.equalsIgnoreCase("y"))
{
FileOutputStream fileOut = new FileOutputStream(file);
int numOfByte;
String str;
do
{
str=inFromClient.readUTF();
numOfByte=Integer.parseInt(str);
if(numOfByte!=-1)
{
fileOut.write(numOfByte);
}
}while(numOfByte!=-1);
fileOut.close();
outToClient.writeUTF("Uploading Completed");
}
else
{
return;
}
}
public void run()
{
while(true)
{
try
{
String str = inFromClient.readUTF();
if(str.equalsIgnoreCase("put"))
{
System.out.println("Accept Uploading...");
ClientUpLoad();
continue;
}
else if(str.equalsIgnoreCase("get"))
{
System.out.println("Accept Downloading");
ClientDownLoad();
continue;
}
else if(str.equalsIgnoreCase("exit"))
{
System.out.println("Accept Exit");
System.exit(1);
}
}catch(Exception e){}
}
}
}
FTPClient.class
public class FTPClient {
public static void main(String[] args) throws Exception
{
final int PORT=22222;
String serverHostname = new String("127.0.0.1");
Socket clientSocket = new Socket(serverHostname, PORT);
clientOperation co=new clientOperation(clientSocket);
co.displaySelection();
}
}
class clientOperation
{
String filePath = "E:" +File.separator+"Studying"+
File.separator+"WorkSpace"+File.separator+"FTPClient"+File.separator;
Socket socket;
DataInputStream inFromServer;
DataOutputStream outToServer;
BufferedReader br;
clientOperation(Socket s)
{
try
{
socket=s;
inFromServer=new DataInputStream(socket.getInputStream());
outToServer=new DataOutputStream(socket.getOutputStream());
br=new BufferedReader(new InputStreamReader(System.in));
}catch(Exception e){}
}
public void ClientUpLoad() throws Exception
{
String fileName;
System.out.println("Enter File Name for uploading: ");
fileName=br.readLine();
String accessfile=filePath + fileName;
System.out.println(accessfile);
File file = new File(accessfile);
if(!file.exists())
{
System.out.println("File Not Found on Client");
outToServer.writeUTF("no such file");
return;
}
outToServer.writeUTF(fileName);
String existingMsg = inFromServer.readUTF();
if(existingMsg.compareToIgnoreCase("File Exists in Server")==0)
{
System.out.println("File Exists in Server. Do you want to replace it? (Y/N)");
String userChoose=br.readLine();
if(userChoose.equalsIgnoreCase("y"))
{
outToServer.writeUTF("y");
}
else if(userChoose.equalsIgnoreCase("n"))
{
outToServer.writeUTF("n");
return;
}
else{
}
}
System.out.println("Uploading...");
FileInputStream fi = new FileInputStream(file);
int numOfByte;
do
{
numOfByte=fi.read();
outToServer.writeUTF(String.valueOf(numOfByte));
}while(numOfByte!=-1);
fi.close();
System.out.println(inFromServer.readUTF());
}
public void ClientDownLoad()throws Exception
{
String fileName;
String userChoose;
System.out.println("Enter File Name for download: ");
fileName=br.readLine();
outToServer.writeUTF(fileName);
String str = inFromServer.readUTF();
if(str.equalsIgnoreCase("FILE NOT FOUND"))
{
System.out.println("File doesn't exist on server...");
return;
}
else if(str.equalsIgnoreCase("Ready for download"))
{
String accessfile=filePath + fileName;
File file=new File(accessfile);
if(file.exists())
{
System.out.println("File exists in Client. Do you want to replace it? (Y/N)");
userChoose=br.readLine();
if(userChoose.equalsIgnoreCase("n"))
{
outToServer.flush();
return;
}
}
FileOutputStream fileOut = new FileOutputStream(file);
int numOfByte;
do
{
numOfByte=Integer.parseInt(inFromServer.readUTF());
if(numOfByte!=-1)
{
fileOut.write(numOfByte);
}
}while(numOfByte!=-1);
fileOut.close();
System.out.println(inFromServer.readUTF());
}
}
public void displaySelection() throws Exception
{
while(true)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please select the number for purpose!");
System.out.println("1. Upload File to Server");
System.out.println("2. Download File from Server");
System.out.println("3. Exit");
System.out.println("Enter your choice: ");
int choice = scan.nextInt();
if(choice ==1)
{
outToServer.writeUTF("put");
ClientUpLoad();
}
else if(choice == 2)
{
outToServer.writeUTF("get");
ClientDownLoad();
}
else
{
outToServer.writeUTF("exit");
System.exit(1);
}
}
}
}

Java Server Sockets: My Server Socket only allows client connections running on the same internet connection?

Ok so I have constructed a working example of a client and server which can accept multiple client connections. My problem is is that I cannot connect a client which is not running the same internet connection as the one the server is being hosted on. Is this possible using server sockets?
Here is the code for my server:
import java.io.IOException;
import java.net.*;
public class MultipleSocketServer {
public static Socket connection;
public static String name = "Tyler's Server";
public static int limit = 2;
public static Thread[] clients = new Thread[limit];
public static int current = 0;
public static int port = 25565;
public static String[] connected = new String[limit];
public static ServerSocket socket;
public static void main(String[] args) {
System.out.println("Server starting...");
for(int i = 0; i < limit; i++) {
connected[i] = "";
}
try {
ServerSocket socket = new ServerSocket(port);
while(true) {
Socket connection = socket.accept();
String ip = connection.getRemoteSocketAddress().toString().substring(1, 13);
loop:
for(int i = 0; i < connected.length; i++) {
if(connected[0].equals(ip) || connected[1].equals(ip)) {
break loop;
}else if(!connected[i].equals(ip)) {
connected[i] = ip;
MultiServer_Client client = new MultiServer_Client(connection, i);
Thread run = new Thread(client);
run.start();
break loop;
}
}
}
} catch (IOException e1) {
System.out.println("Could not bind server on: " + port);
System.exit(-1);
}
}
}
And here is the rest:
import java.io.*;
import java.net.Socket;
public class MultiServer_Client implements Runnable {
public String time;
public Socket client;
public StringBuffer process = new StringBuffer();
public BufferedInputStream inputStream;
public InputStreamReader reader;
public BufferedOutputStream outputStream;
public OutputStreamWriter writer;
public StringVis check = new StringVis("");
public StringChangeListener checkListener = new StringChangeListener() {
public void textChanged(StringChangeEvent e) {
System.out.println("Changed");
write("Server recieved message...");
}
};
public boolean connected = true;
public int ID;
public MultiServer_Client(Socket connection, int i) {
client = connection;
ID = i;
try {
//declare text input/output
inputStream = new BufferedInputStream(client.getInputStream());
reader = new InputStreamReader(inputStream);
outputStream = new BufferedOutputStream(client.getOutputStream());
writer = new OutputStreamWriter(outputStream, "US-ASCII");
} catch (IOException e) {
System.out.println("IOException: " + e);
}
System.out.println(MultipleSocketServer.connected[ID] + " connected...");
write("Connected to " + MultipleSocketServer.name);
}
public void run() {
while(connected) {
read();
}
System.out.println("Disconnecting client...");
}
public void write(String authen) {
try {
time = new java.util.Date().toString();
String message = time + ": " + authen + (char) 13;
writer.write(message);
writer.flush();
} catch (IOException e) {
connected = false;
MultipleSocketServer.connected[ID] = "";
}
}
public void read() {
//read from client
int character;
process = new StringBuffer();
try {
while ((character = reader.read()) != 13) {
process.append((char) character);
}
check.setText(process.toString());
process.delete(0, process.length());
} catch (IOException e) {
connected = false;
MultipleSocketServer.connected[ID] = "";
}
}
}
Here's the client code:
import java.net.*;
import java.util.Scanner;
import java.io.*;
public class SocketClient {
public static String host = "69.182.134.79";
public static int port = 25565;
public static void main(String [] args) {
StringBuffer imports = new StringBuffer();
String time;
System.out.println("Client starting...");
try {
//establish client
InetAddress address = InetAddress.getByName(host);
Socket connection = new Socket(address, port);
BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");
while(true) {
Scanner scan = new Scanner(System.in);
String message = scan.nextLine();
//write to server
time = new java.util.Date().toString();
String process = host + ":" + port + " sent data at " + time + ": " + message + (char) 13;
osw.write(process);
osw.flush();
//read from server
int c;
while ((c = isr.read()) != 13) {
imports.append((char) c);
}
System.out.println(imports);
imports.replace(0, imports.length(), "");
if(message.equals("--EXIT")) {
connection.close();
}
}
} catch (UnknownHostException e) {
System.out.println("UnknownHostException: " + e);
} catch (IOException e) {
System.out.println("IOExcepion: " + e);
}
}
}
Change
MultiServer_Client client = new MultiServer_Client(connection, i);
to
MultiServer_Client client = new MultiServer_Client(new Socket([Server IP], port), i);
This should work.

Categories