Send String from server to client - save it as textfile - java

I know how to send a file from a server to a client but how do I send a textstring to the client where the client save the string as a file? Should I use PrintWriter for this issue?
This is the code for sending a file from server to client:
Sending files through sockets
What I want to do is to (instead of sending a file), sending a String from the server and let the client receive it and save it as a file.
public class SocketFileExample {
static void server() throws IOException {
ServerSocket ss = new ServerSocket(3434);
Socket socket = ss.accept();
InputStream in = new FileInputStream("send.jpg");
OutputStream out = socket.getOutputStream();
copy(in, out);
out.close();
in.close();
}
static void client() throws IOException {
Socket socket = new Socket("localhost", 3434);
InputStream in = socket.getInputStream();
OutputStream out = new FileOutputStream("recv.jpg");
copy(in, out);
out.close();
in.close();
}
static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[8192];
int len = 0;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
}
public static void main(String[] args) throws IOException {
new Thread() {
public void run() {
try {
server();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
client();
}
}

in that case use ObjectOutputStream at server side to write String and use ObjectInputStream at client side to read String coming from server..
so your server() method will look like this..
static void server() throws IOException {
ServerSocket ss = new ServerSocket(3434);
Socket socket = ss.accept();
OutputStream out = socket.getOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(out);
oout.writeObject("your string here");
oout.close();
}
and client() method will look like this..
static void client() throws IOException, ClassNotFoundException {
Socket socket = new Socket("localhost", 3434);
InputStream in = socket.getInputStream();
ObjectInputStream oin = new ObjectInputStream(in);
String stringFromServer = (String) oin.readObject();
FileWriter writer = new FileWriter("received.txt");
writer.write(stringFromServer);
in.close();
writer.close();
}
also throw ClassNotFoundException in main method.
public static void main(String[] args) throws IOException, ClassNotFoundException {.......}
done...

Related

Why cant I write to a socket's input stream java

So I Have two Similar classes to test Sockets that are the same from the lines down.
public class Server {
public static void main(String args[]) throws IOException, InterruptedException {
ServerSocket socket =new ServerSocket(80);
Socket client = socket.accept();
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
//-----------------------------------------------------------------------------------
Scanner s = new Scanner(in);
InputStream txt = System.in;
Scanner text = new Scanner(txt);
while (true) {
if (text.hasNext()) {
out.write((text.next()+"\n").getBytes());
out.flush();
System.out.println("Sent");
}
if (s.hasNext()) {
System.out.println(s.next());
System.out.println("Received");
}
}
}
}
public class Client {
public static void main(String args[]) throws IOException, InterruptedException {
Socket socket =new Socket("localhost",80);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
//-----------------------------------------------------------------------------------
Scanner s = new Scanner(in);
InputStream txt = System.in;
Scanner text = new Scanner(txt);
while (true) {
if (text.hasNext()) {
out.write((text.next()+"\n").getBytes());
out.flush();
System.out.println("Sent");
}
if (s.hasNext()) {
System.out.println(s.next());
System.out.println("Received");
}
}
}
}
The goal is two way messaging.
When I type in either shell it says sent, however no text shows on the other shell.
Why are they not sending or receiving any text?
Any help is greatly appreciated.

readUTF() returns error after writeObject()

I'm setting up a new server-client system. Here from the client, an object will be sent to the server. And after receiving the object the server will send a string to the client.
Here the server reads the object successfully. But when the clients want to read the string sent by the server it throws EOFException.
client-side
public static void main(String args[]) throws IOException, EOFException {
try (Socket socket = new Socket("localhost", 1254)) {
OutputStream outputStream = socket.getOutputStream();
InputStream s1In;
DataInputStream dis;
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream)) {
s1In = socket.getInputStream();
dis = new DataInputStream(s1In);
Frame frame = new Frame();
frame.setData("test");
objectOutputStream.writeObject(frame);
String st = "";
while(dis.available() >0){
st = dis.readUTF();
}
System.out.println(st);
}
dis.close();
s1In.close();
}
}
server-side
public static void main(String args[]) throws IOException, ClassNotFoundException {
ServerSocket s = new ServerSocket(1254);
Socket socket = s.accept();
OutputStream outputStream = socket.getOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
//input stream
InputStream inputStream = socket.getInputStream();
DataInputStream dataInputStream = new DataInputStream(inputStream);
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
Frame frame = new Frame();
frame = (Frame) objectInputStream.readObject();
String data = frame.getData();
System.out.println(data);
// Send a string!
DataOutputStream dos = new DataOutputStream (outputStream);
dos.writeUTF("Received");
dos.close();
objectOutputStream.close();
outputStream.close();
objectInputStream.close();
inputStream.close();
socket.close();
}
error at client side
Exception in thread "main" java.io.EOFException
at java.io.DataInputStream.readFully(DataInputStream.java:197)
at java.io.DataInputStream.readUTF(DataInputStream.java:609)
at java.io.DataInputStream.readUTF(DataInputStream.java:564)
at computernetworklab.Client.main(Client.java:38)
/home/shahad/.cache/netbeans/8.2/executor-snippets/run.xml:53: Java
returned: 1
BUILD FAILED (total time: 0 seconds)

Client-server socket program not experiencing deadlock as expected

I have an example socket program. The client just sends numbers and the server echoes them back.
Client:
public class Client {
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public Client(String hostname, int port) throws IOException {
socket = new Socket(hostname, port);
//Create a BufferedReader with buffer size of 1
in = new BufferedReader(new InputStreamReader(socket.getInputStream()), 1);
out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
}
public void sendRequest(String x) throws IOException {
out.print(x + "\n");
out.flush();
}
public void close() throws IOException {
in.close();
out.close();
socket.close();
}
public String getReply() throws IOException {
String reply = in.readLine();
return reply;
}
public static void main(String[] args) {
try {
Client client = new Client("localhost", 4949);
for (int i = 0; i < 100000; i++){
System.err.println("Sending: "+i);
client.sendRequest(String.valueOf(i));
}
for (int i = 0; i < 100000; i++){
client.getReply();
}
client.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
Server:
public class Server {
private ServerSocket serverSocket;
public Server(int port) throws IOException {
serverSocket = new ServerSocket(port);
}
private void handle(Socket socket) throws IOException {
System.err.println("client connected");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// Create a PrintWriter with buffer size 1
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()), 1));
try {
for (String line = in.readLine(); line != null; line = in.readLine()) {
out.print(line + "\n");
out.flush();
}
} finally {
out.close();
in.close();
}
}
public void serve() throws IOException {
while (true) {
// block until a client connects
Socket socket = serverSocket.accept();
try {
handle(socket);
} catch (IOException ioe) {
ioe.printStackTrace(); // but don't terminate serve()
} finally {
socket.close();
}
}
}
public static void main(String[] args) {
try {
Server server = new Server(4949);
server.serve();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This may seem like an obvious question, but why is the input buffer to the Client not filling up and causing deadlock? The Client sends 10000 numbers before ever reading any replies. Wouldn't this cause the client's receive buffer to fill up, also causing the server's sending buffer to fill up? I even make the buffer size for the BufferedReader and BufferedWriter as small as possible.However, when I run this code, there is no deadlock.
Because you're overlooking the existence of the socket send buffer at the sender, and the socket receive buffer at the receiver. These are in the kernel, and they can clearly hold all the server's output between them.

Sending Strings through Sockets

Here is the Server
public class SocketMsg {
public static void main(String[] args) throws IOException{
ServerSocket ss = new ServerSocket("number goes here");
System.out.println("Server Ready");
ss.accept();
}
}
Client:
public class SocketMesg {
public static void main(String[] args) throws IOException{
Socket socket = null;
OutputStreamWriter osw;
String str = "Hello World";
try {
socket = new Socket("localhost", "number goes here");
osw =new OutputStreamWriter(socket.getOutputStream());
osw.write(str, 0, str.length());
} catch (IOException e) {
System.err.print(e);
}
finally {
socket.close();
}
}
Personally, the code works but the strings are not sending to the other host, I gave them the same number, but it is not working. The client is sending it back to the server on the DOS window. Did I make a error? What did I do wrong?
Your server-side at least needs the following.
Socket clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
// process inputLine;
}
You need to flush outputstream to commit write buffer to the socket. Also be careful with charset if writing strings. This example explicitly uses UTF-8 through "low level" byte array buffer. I think you are practicing your first socket programming so I kept this very simple.
Server.java
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(1122);
System.out.println("Server Ready");
while(true) {
Socket socket = ss.accept();
InputStream is = socket.getInputStream();
// client must send 1-10 bytes, no more in single command
byte[] buf = new byte[10];
int read = is.read(buf, 0, buf.length);
String cmd = new String(buf, 0, read, "UTF-8");
System.out.println(cmd);
socket.close(); // we are done, this example reads input and then closes socket
}
}
}
Client.java
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws Exception {
Socket socket = null;
// send max of 10 bytes to simplify this example
String str = "ABCDEFGHIJ";
try {
socket = new Socket("localhost", 1122);
OutputStream os = socket.getOutputStream();
byte[] buf = str.getBytes("UTF-8");
os.write(buf, 0, buf.length);
os.flush();
} catch (IOException ex) {
System.err.print(ex);
} finally {
socket.close();
}
}
}

not able to transfer Image file

hi this is my client program for transfering Image , while transfering the image file it is getting corrupted , not able to open that image file , i'm not able to identify the bug , can any one help me.
DataInputStream input = new DataInputStream(s.getInputStream());
DataOutputStream output = new DataOutputStream(s.getOutputStream());
System.out.println("Writing.......");
FileInputStream fstream = new FileInputStream("Blue hills.jpg");
DataInputStream in = new DataInputStream(fstream);
byte[] buffer = new byte[1000];
int bytes = 0;
while ((bytes = fstream.read(buffer)) != -1) {
output.write(buffer, 0, bytes);
}
in.close();
I assume that s is a Socket and you're attempting to transfer a file over the network? Here's an example of sending a file with sockets. It just sets up a server socket in a thread and connects to itself.
public static void main(String[] args) throws IOException {
new Thread() {
public void run() {
try {
ServerSocket ss = new ServerSocket(3434);
Socket socket = ss.accept();
InputStream in = socket.getInputStream();
FileOutputStream out = new FileOutputStream("out.jpg");
copy(in, out);
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
Socket socket = new Socket("localhost", 3434);
OutputStream out = socket.getOutputStream();
FileInputStream in = new FileInputStream("in.jpg");
copy(in, out);
out.close();
in.close();
}
public static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[8192];
int len = 0;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
}

Categories