spawn another port on localhost FTP server to handle data - java

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);
}
}
}
}

Related

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();
}
}

Please with multithreading in 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.

print BufferedReader while Socket remains open

What I want are just the responses from wunderground printed to the console:
public class Weather {
public static void main(String[] args) {
String host = "rainmaker.wunderground.com";
int port = 3000;
int c;
{
try (Socket socket = new Socket(host, port);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))) {
while (true) {
System.out.println(socket.toString());
c = bufferedReader.read();
System.out.print((char) c);
}
} catch (IOException ex) {
System.out.println(ex + host + port);
System.exit(1);
} finally {
System.exit(1);
}
}
}
}
However, there's not much output to go on:
thufir#dur:~/NetBeansProjects/MudSocketClient$
thufir#dur:~/NetBeansProjects/MudSocketClient$ java -jar dist/MudSocketClient.jar
Socket[addr=rainmaker.wunderground.com/38.102.137.140,port=3000,localport=53550]
^Cthufir#dur:~/NetBeansProjects/MudSocketClient$
thufir#dur:~/NetBeansProjects/MudSocketClient$
Running telnet from the CLI, the connection works fine.
I found some old code:
public class InputOutput extends Observable {
private static final Logger log = Logger.getLogger(InputOutput.class.getName());
private Alias alias = new Alias();
public InputOutput() {
}
private void readFromConsole(final OutputStream outputStream) {
Thread read = new Thread() {
#Override
public void run() {
String line;
byte[] bytes;
Scanner scanner;
while (true) {
GameDataBean gameData = null;
scanner = new Scanner(System.in);
line = scanner.nextLine();
try {
gameData = alias.parseUserInput(line);
} catch (StringIndexOutOfBoundsException e) {
log.fine(e.toString());
}
if (gameData != null) {
setChanged();
notifyObservers(gameData);
} else {
bytes = line.getBytes();
try {
outputStream.write(bytes);
outputStream.write(10);
outputStream.flush();
} catch (IOException ex) {
log.fine(ex.toString());
}
}
}
}
};
read.start();
}
private void readInput(final InputStream inputStream) throws FileNotFoundException, IOException {
Thread readInput = new Thread() {
#Override
public void run() {
char ch = 0;
int intVal = 0;
StringBuilder sb = new StringBuilder();
try {
while ((intVal = inputStream.read()) != -1) {
ch = (char) intVal;
printToConsole(ch);
//logToFile(ch);
sb.append(ch);
if (intVal == 13) {
setChanged();
notifyObservers(sb.toString());
sb = new StringBuilder();
}
}
} catch (IOException ex) {
Logger.getLogger(InputOutput.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void logToFile(char c) throws IOException {
String fname = "weather.log";
File f = new File(fname);
f.createNewFile();
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fname, true)))) {
out.print(c);
out.flush();
}
}
private void printToConsole(char c) {
System.out.print(c);
}
};
readInput.start();
}
public void readWriteParse(final InputStream inputStream, final OutputStream outputStream) throws FileNotFoundException, IOException {
readFromConsole(outputStream);
readInput(inputStream);
}
}
I think it's that, when the socket is still open, it has to be multi-threaded, as I recall.

java.net.SocketException: Connection Reset

I'm trying to write a socket program where a string is sent to the server, reversed and the reversed string is sent back to the client.
Here's my server code:
import java.io.*;
import java.net.*;
class ClientSystem
{
public static void main(String[] args)
{
String hostname = "127.0.0.1";
int port = 1234;
Socket clientsocket = null;
DataOutputStream output =null;
BufferedReader input = null;
try
{
clientsocket = new Socket(hostname,port);
output = new DataOutputStream(clientsocket.getOutputStream());
input = new BufferedReader(new InputStreamReader(clientsocket.getInputStream()));
}
catch(Exception e)
{
System.out.println("Error occured"+e);
}
try
{
while(true)
{
System.out.println("Enter input string ('exit' to terminate connection): ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inputstring = br.readLine();
output.writeBytes(inputstring+"\n");
//int n = Integer.parseInt(inputstring);
if(inputstring.equals("exit"))
break;
String response = input.readLine();
System.out.println("Reversed string is: "+response);
}
output.close();
input.close();
clientsocket.close();
}
catch(Exception e)
{
System.out.println("Error occured."+e);
}
/*finally
{
output.close();
input.close();
clientsocket.close();
}*/
}
}
Here's my server code:
import java.io.*;
import java.net.*;
public class ServerSystem
{
ServerSocket server = null;
Socket clientsocket = null;
int numOfConnections = 0, port;
public ServerSystem(int port)
{
this.port = port;
}
public static void main(String[] args)
{
int port = 1234;
ServerSystem ss = new ServerSystem(port);
ss.startServer();
}
public void startServer()
{
try
{
server = new ServerSocket(port);
}
catch(Exception e)
{
System.out.println("Error occured."+e);
}
System.out.println("Server has started. Ready to accept connections.");
while(true)
{
try
{
clientsocket = server.accept();
numOfConnections++;
ServerConnection sc = new ServerConnection(clientsocket, numOfConnections, this);
new Thread(sc).start();
}
catch(Exception e)
{
System.out.println("Error occured."+e);
}
}
}
public void stopServer()
{
System.out.println("Terminating connection");
System.exit(0);
}
}
class ServerConnection extends Thread
{
BufferedReader br;
PrintStream ps;
Socket clientsocket;
int id;
ServerSystem ss;
public ServerConnection(Socket clientsocket, int numOfConnections, ServerSystem ss)
{
this.clientsocket = clientsocket;
id = numOfConnections;
this.ss = ss;
System.out.println("Connection "+id+" established with "+clientsocket);
try
{
br = new BufferedReader(new InputStreamReader(clientsocket.getInputStream()));
ps = new PrintStream(clientsocket.getOutputStream());
}
catch(Exception e)
{
System.out.println("Error occured."+e);
}
}
public void run()
{
String line;
try
{
boolean stopserver = false;
while(true)
{
line = br.readLine();
System.out.println("Received string: "+line+" from connection "+id);
long threadID = Thread.currentThread().getId();
System.out.println("Thread ID: "+threadID+" is doing the current task.");
if(line.equals("exit"))
{
stopserver = true;
break;
}
else
{
int len = line.length();
String reversedstring = "";
for (int i=len-1; i>=0; i--)
reversedstring = reversedstring + line.charAt(i);
ps.println(""+reversedstring);
}
}
System.out.println("Connection "+id+" is closed.");
br.close();
ps.close();
clientsocket.close();
if(stopserver)
ss.stopServer();
}
catch(Exception e)
{
System.out.println("Error occured."+e);
}
}
}
I'm trying to open two clients. When I type "exit" in one of the clients (say client1), the server itself is terminating. But I don't want the server to close but just the connection to client1 to close. When I next type a string in client2, I get "java.net.SocketException: Connection Reset" .
How do I get rid of the exception and the connection at server be still open for client2?
It's your code:
while(true){
...
if(line.equals("exit"))
{
stopserver = true;
break;
}
...
}
...
if(stopserver)
ss.stopServer();

Overriding the run() method to accept a parameter from the command line

I'm trying to search a word (from a file) specified in the command line using client/server. Here is my code, however it displays nothing when the client part is run. To run the server, type -s <port number> <file.txt> and for the client, -c localhost <port number> <word to be searched> in the command line.
import java.net.*;
import java.util.*;
import java.io.*;
public class quotes {
public static InetAddress host;
public static ServerSocket serverSocket;
public static String target;
public static void main(String[] args) throws IOException {
if(args[0].equals("-c")){
Client(args);
target = args[3];
}
else if(args[0].equals("-s")){
System.out.println("Server");
Server(args);
}
}
#SuppressWarnings("resource")
public static void Client(String[] args) throws IOException{
String hostname = args[1];
if(hostname.equals("localhost")) host = InetAddress.getLocalHost();
else host = InetAddress.getByName(hostname);
int port = Integer.parseInt(args[2]);
Socket socket = new Socket(host, port);
Scanner input = new Scanner(System.in);
Scanner networkInput = new Scanner(socket.getInputStream());
PrintWriter networkOutput = new PrintWriter(socket.getOutputStream(), true);
Scanner userEntry = new Scanner(System.in);
String response;
networkOutput.println(target);
response = networkInput.nextLine();
while(!response.equals("|")){
System.out.println("\n " + response);
response = networkInput.nextLine();
}
}
public static void Server(String[] args) throws IOException {
int port = Integer.parseInt(args[1]);
String file = args[2];
serverSocket = new ServerSocket(port);
do {
Socket client = serverSocket.accept();
System.out.println("\nNew client accepted.\n");
ClientHandler3 handler = new ClientHandler3(client, file);
handler.start();
}while(true);
}
}
class ClientHandler3 extends Thread {
private Socket client;
private Scanner input;
private PrintWriter output;
private ArrayList<String> quotes;
public ClientHandler3(Socket socket, String file) {
client = socket;
try {
BufferedReader buffer = new BufferedReader(new FileReader(file));
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = reader.readLine();
try {
int ctr = 0;
quotes = new ArrayList<String>();
while(line != null){
quotes.add(ctr, line);
ctr++;
line = buffer.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
input = new Scanner(client.getInputStream());
output = new PrintWriter(client.getOutputStream(), true);
}
catch(IOException e) {
e.printStackTrace();
}
}
public void run() {
String target;
String message = "";
target= args[3];
for(int i = 0; i<quotes.size(); i++){
if(quotes.get(i).toUpperCase().contains(target.toUpperCase())){
output.println(quotes.get(i));
}
}
output.println("|");
try {
if (client != null) {
System.out.println("Closing down connection...");
client.close();
}
}
catch(IOException e) {
System.out.println("Unable to disconnect!");
}
}
}
(Thanks to Sir JB Nizet for some modifications and advice) I'm having a problem in target= args[3]; in class ClientHandler3 because I know it makes no sense in overriding. I'm new in this field of programming and I need your help. Please help me figure things out. Thank you!
EDIT
import java.net.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.*;
public class quotes {
public static InetAddress host;
public static ServerSocket serverSocket;
public static void main(String[] args) throws IOException {
if(args[0].equals("-c")){
Client(args);
}
else if(args[0].equals("-s")){
System.out.println("SERVER KA!!!");
Server(args);
}
}
#SuppressWarnings("resource")
public static void Client(String[] args) throws IOException
String hostname = args[1];
String target, response;
if(hostname.equals("localhost")) host = InetAddress.getLocalHost();
else host = InetAddress.getByName(hostname);
int port = Integer.parseInt(args[2]);
target = args[3];
Socket socket = new Socket(host, port);
Scanner input = new Scanner(System.in);
Scanner networkInput = new Scanner(socket.getInputStream());
PrintWriter networkOutput = new PrintWriter(socket.getOutputStream(), true);
// Set up stream from keyboard entry...
Scanner userEntry = new Scanner(System.in);
networkOutput.println(target);
response = networkInput.nextLine();
while(!response.equals("|")){
// Display server's response to user ...
System.out.println("\n " + response);
response = networkInput.nextLine();
}
}
public static void Server(String[] args) throws IOException {
int port = Integer.parseInt(args[1]);
String file = args[2];
String target = "";
serverSocket = new ServerSocket(port);
do {
// Wait for client...
Socket client = serverSocket.accept();
System.out.println("\nNew client accepted.\n");
ClientHandler3 handler = new ClientHandler3(client, file, target);
handler.start();
}while(true);
}
}
class ClientHandler3 extends Thread {
private Socket client;
private Scanner input;
private PrintWriter output;
private ArrayList<String> quotes;
private String target;
public ClientHandler3(Socket socket, String file, String target) {
// Set up reference to associated socket...
client = socket;
try {
BufferedReader buffer = new BufferedReader(new FileReader(file));
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
this.target = reader.readLine();
String line = reader.readLine();
try {
int ctr = 0;
quotes = new ArrayList<String>();
while(line != null){
quotes.add(ctr, line);
ctr++;
line = buffer.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
input = new Scanner(client.getInputStream());
output = new PrintWriter(client.getOutputStream(), true);
}
catch(IOException e) {
e.printStackTrace();
}
}
public void run() {
String message = "";
target= input.nextLine();
for(int i = 0; i<quotes.size(); i++){
if(quotes.get(i).toUpperCase().contains(target.toUpperCase())){
output.println(quotes.get(i));
}
}
output.println("|");
try {
if (client != null) {
System.out.println("Closing down connection...");
client.close();
}
}
catch(IOException e) {
System.out.println("Unable to disconnect!");
}
}
}
Set target as a field of ClientHandler3 so you can use it inside run() method.
class ClientHandler3 extends Thread {
...
private String target;
...
and use:
this.target = reader.readLine();
just before
String line = reader.readLine();
line.

Categories