How can I transfer files from Server-Side to Client using Sockets? - java

I'm having trouble on where to begin performing this task, I'd like some examples or input on how I should set up my server/client components to receive and send data including letting the client download images.
Here's my client-side code:
package V3;
import java.io.*;
import java.net.*;
public class Version3Client {
public static void main(String[] args) throws IOException {
Socket kkSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
kkSocket = new Socket("localhost", 4444);
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: taranis.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Bye."))
break;
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
out.close();
in.close();
stdIn.close();
kkSocket.close();
}
}
And here's my server-side code:
package V3;
import java.net.*;
import java.io.*;
public class Version3Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(-1);
}
while (listening)
new Version3ServerThread(serverSocket.accept()).start();
serverSocket.close();
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine, outputLine;
Version3Protocol kkp = new Version3Protocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
Thread class added for further specification:
package V3;
import java.net.*;
import java.io.*;
import java.io.FileWriter;
public class Version3ServerThread extends Thread {
private Socket socket = null;
public Version3ServerThread(Socket socket) {
super("Version3ServerThread");
this.socket = socket;
}
public void run() {
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
String inputLine, outputLine;
Version3Protocol kkp = new Version3Protocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye"))
break;
if(kkp.getInteraction()){
Logging.writeToFile(socket.getInetAddress());
}
}
out.close();
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

The code so far, the client-server-communication without the file-transfer ability, looks fine to me. I wanted to compile to find any errors but you didnt include Version3Protocol and Logging. If it does compile then your next step would be to open the file you want to transfer on the server with a FileInputStream and a new file for writing on the client with FileOutputStream:
http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileInputStream.html
http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileOutputStream.html
You can then read the file into buffer, transfer it using the socket, receive it on the client-side, and copy the buffer-contents into the FileOutputStream there.

Related

Android Client Socket IOException

EDIT: The problem is the input in the Client.class so when the Android devices receives an answer from the Server. Those are the following lines that causes the crash:
InputStream input = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String text;
while ((text = reader.readLine()) != null) {
Log.d("ClientLog", "Received from Server"+ text);
}
Here is my Client.class in Android:
public class Client implements Runnable{
public Client() {
}
#Override
public void run() {
try {
Log.d("ClientLog", "Socket creation incoming");
Socket client = new Socket("localhost", 5555);
Log.d("ClientLog", "Client has been started");
// Streams:
OutputStream out = client.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
InputStream input = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
// -----------------------------------------------------------------------
writer.write("Test");
writer.newLine();
writer.flush();
String text;
while ((text = reader.readLine()) != null) {
Log.d("ClientLog", "Received from Server"+ text);
}
writer.close();
reader.close();
} catch (UnknownHostException e) {
Log.d("ClientLog", "Error: Host not found");
e.printStackTrace();
} catch (IOException e) {
Log.d("ClientLog", "Error: IOException");
e.printStackTrace();
}
}
}
And if needed my Server.class in Java:
public class Server {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(30);
ServerSocket server;
try {
server = new ServerSocket(5555);
System.out.println("Server has been started on Port 5555");
while(true) {
try {
Socket client = server.accept();
//Thread t = new Thread(new Handler(client));
//t.start();
executor.execute(new Handler(client));
} catch (IOException e) {
System.out.println("Error IOExceotion");
e.printStackTrace();
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
The Handler.class needed for Server.class:
public class Handler implements Runnable{
private Socket client;
public Handler(Socket pClient) {
client = pClient;
}
#Override
public void run() {
try {
// Streams:
OutputStream out = client.getOutputStream();
PrintWriter writer = new PrintWriter(out);
InputStream input = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
// -----------------------------------------------------------------------
String text = null;
while ((text = reader.readLine()) != null) {
writer.write(text+ "\n");
writer.flush();
System.out.println("Recieved from Client: "+ text);
}
//Close Streams
writer.close();
reader.close();
client.close();
} catch (IOException e) {
System.out.println("Error IOException");
e.printStackTrace();
}
}
}
The debugging was resolved in the comments above.
Step 1: Add permissions to the android manifest file as was outlined here: Java socket IOException - permission denied
Step 2: Change the while ((text = reader.readLine()) != null) check. I guess the text = reader.readLine() != null check was problematic.

While loop in client-server program

so i was i have to do some simple client-server program.
Server side
`
public static void main(String[] args) throws IOException
{
ServerSocket ss = null;
try{ss= new ServerSocket(119);}
catch(IOException ioe){System.out.println("Can't connect to port.");}
Socket sock = null;
try{sock = ss.accept();}
catch(IOException ioe){System.out.println("Can't connect to client.");}
System.out.println("Connection successful.");
PrintStream out = null;
Scanner in = null;
try{
out = new PrintStream(sock.getOutputStream());
in = new Scanner(sock.getInputStream());
}catch(Exception e)
{
System.out.println("Error.");
}
String line;
String lines = "";
while((line = in.nextLine()) != null)
{
switch(line)
{
case "list":out.println("Printing something");break;
case "loop":
{
FileReader fr = new FileReader("D:\\Eclipse\\TestFiles\\text2.txt");
BufferedReader br = new BufferedReader(fr);
while((lines = br.readLine()) != null)
{
out.println(lines);
}
break;
}
default:
{
if(!(line.equals("end"))) out.println("Unknown command.Try again.");break;
}
}
out.flush();
if(line.equals("end"))
{
out.println("Connection over.");
break;
}
}
try{
in.close();
out.close();
sock.close();
ss.close();
}catch(IOException ioe){}
}
`
Client side
public static void main(String[] args)
{
Socket sock = null;
PrintStream out = null;
Scanner in = null;
Scanner sIn = null;
try{
sock = new Socket("localhost",119);
out = new PrintStream(sock.getOutputStream());
in = new Scanner(sock.getInputStream());
sIn = new Scanner(System.in);
}catch(Exception e){
System.out.println("Error connecting to server.");
System.exit(1);
}
System.out.println("Connection successful.");
String temp = "";
while((temp = sIn.nextLine()) != null)
{
out.println(temp);
while(in.hasNextLine())System.out.println(in.nextLine());
out.flush();
if(temp.equals("end")) break;
}
try{
sock.close();
in.close();
out.close();
}catch(IOException ioe){}
}
My problem is that on the client side when the second while loop(the on inside the first while loop) has to end, it does not and i am just entering commands in the client without any response
Fixes
Use PrintWriter for to write to the socket and BufferedReader to read from the socket. Open the PrintWriter in auto flush mode true in the below statement signifies that. This way you don't have to worry about flushing the stream.
PrintWriter out = new PrintWriter(sock.getOutputStream(),true);
Your closing statements are within loop, which closes streams and you cannot use them for the next iteration because you will get an exception. Pull them out of the while loop.
Unnecessary braces to delimit cases in the switch.
Your connection termination statements should be out of the switch case. Only then break will have a effect on the loop instead on the switch.
I used br.ready() to sense if the stream is ready to be read and then iterating through the loop. This is effective than your version.
while((temp = sIn.nextLine()) != null)
{
out.println(temp);
Thread.currentThread().sleep(1000);
while(in.ready())System.out.println(in.readLine());
out.flush();
if(temp.equals("end")) break;
}
Thread.currentThread().sleep(1000), is to get handle of the main thread and sleep it for 1000ms, this way I am letting br be ready with the server response. otherwise br.ready() will be false, for the present request, and it gets ready in the next iteration. I think you know what I trying to convey.
I did not check the case loop;
Server
import java.net.*;
import java.io.*;
import java.util.*;
public class chatServer
{
public static void main(String[] args) throws IOException
{
ServerSocket ss = null;
try
{
ss= new ServerSocket(8000);
}
catch(IOException ioe){System.out.println("Can't connect to port.");}
Socket sock = null;
try{sock = ss.accept();}
catch(IOException ioe){System.out.println("Can't connect to client.");}
System.out.println("Connection successful.");
PrintWriter out = null;
Scanner in = null;
try{
out = new PrintWriter(sock.getOutputStream(),true);
in = new Scanner(sock.getInputStream());
}catch(Exception e)
{
System.out.println("Error.");
}
String line;
String lines = "";
while((line = in.nextLine()) != null)
{
switch(line)
{
case "list":
out.println("1. bla | 2. ble | 3. bli");break;
case "group":out.println("Here group will be chosen.");break;
case "header":out.println("Returns header.");break;
case "loop":
FileReader fr = new FileReader("D:\\Eclipse\\TestFiles\\text2.txt");
BufferedReader br = new BufferedReader(fr);
while((lines = br.readLine()) != null)
{
out.println(lines);
}
break;
default:
if(!(line.equals("end")))
{
out.println("Unknown command.Try again.");
break;
}
}
if(line.equals("end"))
{
out.println("Connection over.");
break;
}
}
try{
in.close();
out.close();
sock.close();
ss.close();
}catch(IOException ioe){}
}
}
Client
import java.net.*;
import java.io.*;
import java.util.*;
public class chatClient
{
public static void main(String[] args) throws IOException, InterruptedException
{
Socket sock = null;
PrintStream out = null;
BufferedReader in = null;
Scanner sIn = null;
try
{
sock = new Socket("localhost",8000);
out = new PrintStream(sock.getOutputStream());
in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
sIn = new Scanner(System.in);
}
catch(Exception e)
{
System.out.println("Error connecting to server.");
System.exit(1);
}
System.out.println("Connection successful.");
String temp = "";
while((temp = sIn.nextLine()) != null)
{
out.println(temp);
Thread.currentThread().sleep(1000);
while(in.ready())System.out.println(in.readLine());
out.flush();
if(temp.equals("end")) break;
}
try
{
sock.close();
in.close();
out.close();
}
catch(IOException ioe){}
}
}

BufferedReader from server does not work

In this code I can correctly receive a request using BufferedReader inClient, created on the client socket.
Then I send the request to the server and I see the server gets it.
But then, when I try to read the reply from the server (using BufferedReader inServer on the socket of the server), it always ends in IOException: Impossible read from server.
I am referring to the block ################
Do you know any possible reasons?
import java.io.*;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class ProxyMain {
public static void main(String argv[]) {
int proxyPort = 55554;
String proxyAddr = "127.0.0.1";
ServerSocket proxySocket = null;
try {
proxySocket = new ServerSocket(proxyPort, 50, InetAddress.getByName("127.0.0.1"));
}
catch (Exception e) {
System.err.println("Impossible to create socket server!");
System.out.flush();
System.exit(1);
}
System.out.printf("Proxy active on port: %d and on address %s\n", proxyPort, proxySocket.getInetAddress());
System.out.println();
while (true) {
Socket client = null;
Socket sockServ = null;
BufferedReader inClient = null;
PrintWriter outClient = null;
BufferedReader inServer = null;
PrintWriter outServer = null;
String request = new String();
String tmp = new String();
String reply = new String();
String tmpReply = new String();
try {
client = proxySocket.accept();
System.out.println("Connected to: ");
System.out.println(client.getInetAddress().toString());
System.out.printf("On port %d\n", client.getPort());
System.out.println();
inClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
outClient = new PrintWriter(client.getOutputStream(), true);
}
/*catch (IOException e) {
System.err.println("Couldn't get I/O for connection accepted");
System.exit(1);
}*/
catch (Exception e) {
System.out.println("Error occurred!");
System.exit(1);
}
System.out.println("Received request:");
try{
for (int i = 0; i<2; i++) {
tmp = inClient.readLine();
request = request + tmp;
}
inClient.close();
}
catch (IOException ioe) {
System.err.println("Impossible to read mhttp request!");
System.exit(1);
}
System.out.println(request);
System.out.println();
try {
sockServ = new Socket("127.0.0.1", 55555);
outServer = new PrintWriter(sockServ.getOutputStream(), true);
inServer = new BufferedReader(new InputStreamReader(sockServ.getInputStream()));
}
catch (UnknownHostException e) {
System.err.println("Don't know about host: 127.0.0.1:55555");
System.exit(1);
}
catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: 127.0.0.1:55555");
System.exit(1);
}
outServer.println(request);
outServer.close();
try {
#################################################
while ((tmpReply = inServer.readLine()) != null) {
System.out.println(tmpReply);
reply = reply + tmpReply;
}
inServer.close();
sockServ.close();
}
catch (IOException ioe) {
System.err.println("Impossible to read from server!");
System.exit(1);
}
outClient.println(reply);
outClient.close();
try {
client.close();
}
catch (IOException ioe) {
System.err.printf("Impossible to close connection with %s:%d\n", client.getInetAddress().toString(), client.getPort());
}
}
}
}
UPDATE:
It seems that if I do:
boolean res = inServer.ready();
it always return false.
So Server is not ready to send the reply but this is strange...with my Project in C e Python it worked immediately. Why should java be different?
When you close outServer, you close the underlying socket. if you just want to close the output and keep the input open, you need to use Socket.shutdownOutput(). note, you have the same problem when you close inClient.
This works, maybe you can get some ideas from it...
ChatServer - broadcasts to all connected clients
In one command prompt: java ChartServer
In another: java ChatClient localhost (or the ip address of where the server is running)
And another: java ChatClient localhost (or the ip address of where the server is running)
Start chatting in the client windows.
Server like this...
// xagyg wrote this, but you can copy it
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
public static List list = new ArrayList();
public static void main(String[] args) throws Exception {
ServerSocket svr = new ServerSocket(4444);
System.out.println("Chat Server started!");
while (true) {
try {
Socket s = svr.accept();
synchronized(list) {
list.add(s);
}
new Handler(s, list).start();
}
catch (IOException e) {
// print out the error, but continue!
System.err.println(e);
}
}
}
}
class Handler extends Thread {
private Socket s;
private String ipaddress;
private List list;
Handler (Socket s, List list) throws Exception {
this.s = s;
ipaddress = s.getInetAddress().toString();
this.list = list;
}
public void run () {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
String message;
//MyDialog x = (MyDialog)map.get(ipaddress.substring(1));
while ((message = reader.readLine()) != null) {
if (message.equals("quit")) {
synchronized(list) {
list.remove(s);
}
break;
}
synchronized(list) {
for (Object object: list) {
Socket socket = (Socket)object;
if (socket==s) continue;
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.println(ipaddress + ": " + message);
writer.flush();
}
}
}
try { reader.close(); } catch (Exception e) {}
}
catch (Exception e) {
System.err.println(e);
}
}
}
Client like this ...
// xagyg wrote this, but you can copy it
import java.util.*;
import java.io.*;
import java.net.*;
public class ChatClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket(args[0], 4444);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String message;
new SocketReader(in).start();
while ((message = reader.readLine())!=null) {
out.println(message);
out.flush();
if (message.equals("quit")) break;
}
in.close();
out.close();
}
}
class SocketReader extends Thread {
BufferedReader in;
public SocketReader(BufferedReader in) {
this.in = in;
}
public void run() {
String message;
try {
while ((message = in.readLine())!=null) {
System.out.println(message);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}

Java Sockets - A Client that reads the data the server gets

I am working on a java socket program and have difulcites with the client part. The server get's what all the clients write, but the client only gets what it writes. Could someone provide me with an example of a client part of a program that gets what all the clients write? Thanks!
Here is an "echo server" example
import java.io.*;
import java.net.*;
class TCPServer
{
public static void main(String argv[]) throws IOException
{
ServerSocket serverSocket = null;
DataInputStream serverInput = null;
PrintStream serverOutput = null;
String line = null;
Socket clientSocket = null;
// create server socket
try
{
serverSocket = new ServerSocket(2012);
clientSocket = serverSocket.accept();
serverInput = new DataInputStream(clientSocket.getInputStream());
serverOutput = new PrintStream(clientSocket.getOutputStream());
}
catch(IOException e){System.out.println(e);}
// receive data and send it back to the client
try
{
while(true)
{
line = serverInput.readLine();
if(line.equals("exit"))
{
break;
}
else
{
if(!line.equals(null) && !line.equals("exit"))
{
System.out.println("Received " +line);
line = line+" MODIFIED";
serverOutput.println(line);
}
}
}
}
catch(IOException e){System.out.println("SERVER SIDE: Unable send/receive data");}
try
{
serverInput.close();
serverOutput.close();
clientSocket.close();
serverSocket.close();
}
catch(IOException e){System.out.println(e);}
}
}
Here is the client
import java.io.*;
import java.net.*;
public class TCPClient
{
public static void main(String[] args) throws IOException
{
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("localhost", 2012);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
if(userInput.equals("exit"))
break;
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}

Console based login application using java sockets

I am making a console based java application - which will check the username and password of client. What I want is the data entered by client must enter to server in a line by line format i.e pressing enter must send username data and password for next enter press. But what the problem is - until I quit at the client side the data is not sent to the server. Meaning , when client hits 'Bye.' then the client is closed and server receives the data then. Help me in this regard as this is the first step - later I have to check database with this username and password on server. My codes are as follows :
Server :
import java.net.*;
import java.io.*;
public class EchoServer2 extends Thread
{
protected Socket clientSocket;
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(2010);
System.out.println ("Connection Socket Created");
try {
while (true)
{
System.out.println ("Waiting for Connection");
new EchoServer2 (serverSocket.accept());
}
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
}
catch (IOException e)
{
System.err.println("Could not listen on port.");
System.exit(1);
}
finally
{
try {
serverSocket.close();
}
catch (IOException e)
{
System.err.println("Could not close port.");
System.exit(1);
}
}
}
private EchoServer2 (Socket clientSoc)
{
clientSocket = clientSoc;
start();
}
public void run()
{
System.out.println ("New Communication Thread Started");
try {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
PrintWriter out1 = new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
BufferedReader in1 = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
String inputLine,u,p;
while ((u = in.readLine()) != null && (p = in.readLine()) != null)
{
System.out.println ("U: " + u);
out1.println(u);
System.out.println ("P: " + p);
out1.println(p);
if (u.equals("Bye."))
break;
}
out1.close();
out.close();
//in1.close();
in.close();
clientSocket.close();
}
catch (IOException e)
{
System.err.println("Problem with Communication Server");
System.exit(1);
}
}
}
Client :
import java.io.*;
import java.net.*;
import java.lang.*;
import java.io.Console;
public class EchoClient2 {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname + " on port .");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
BufferedReader in1 = null;
try {
echoSocket = new Socket(serverHostname, 2010);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
BufferedReader std = new BufferedReader(
new InputStreamReader(System.in));
String upwd,uname,text;
Console console = System.console();
String username = console.readLine("Username:");
char[] pwd = console.readPassword("Password:");
upwd=new String(pwd);
while (username!=null && upwd!=null && (uname = stdIn.readLine()) != null)
{
out.println("Username:"+username);
out.println("Password:"+upwd);
// end loop
if (uname.equals("Bye."))
break;
}
out.close();
stdIn.close();
echoSocket.close();
}
}
On the client side, do out.flush() after writing the password to the stream.

Categories