I'm trying to send a file between server and client but when I'm trying to write into socket I'm getting java.net.SocketException: Connection reset by peer: socket write error.
//server side
package tcp;
import java.net.*;
import java.io.*;
import java.sql.Connection;
import java.util.*;
public class ServerSock {
static ServerSocket Socket1;
static int port=2500;
public static void main(String[] args) {
Socket server;
File filename=new File("C:/Users/Sudhir/Desktop/mot.wmv");
byte[] serverBuffer=new byte[(int)filename.length()];
StringBuffer msgFromClient= new StringBuffer();
String timeStamp;
try {
Socket1=new ServerSocket(port);
System.out.println("Server Socket is initialised");
int c;
server=Socket1.accept();
BufferedInputStream serverInputBuffer = new BufferedInputStream(server.getInputStream());
InputStreamReader serverInputStream = new InputStreamReader(serverInputBuffer);
while((c=serverInputStream.read())!=13) {
msgFromClient.append((char)c);
}
System.out.println(msgFromClient);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
timeStamp=new Date().toString();
//String filename = "test.pdf";
//byte[] serverBuffer=new byte[1024*33];
String respond = "Server responded at "+ timeStamp + (char) 13;
//System.out.println(respond);
//BufferedOutputStream bos = new BufferedOutputStream(server.getOutputStream());
//OutputStreamWriter osw = new OutputStreamWriter(bos);
FileInputStream fis=new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(serverBuffer,0,serverBuffer.length);
OutputStream os=server.getOutputStream();
try{
os.write(serverBuffer,0,serverBuffer.length);
}catch(IOException e2){
System.out.println(e2);
}
//String serverMessage=new String(serverBuffer);
//serverMessage+=(char)13;
//osw.write(respond);
os.flush();
server.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
//clientside
package tcp;
import java.io.*;
import java.net.*;
import java.util.*;
public class ClientSocket {
public static void main(String[] args) {
String host="127.0.0.1";
int port=2500;
StringBuffer msgFromServer = new StringBuffer();
String timeStamp;
byte clientBuffer[]=new byte[732419705];
System.out.println("Client Socket is initialised");
try {
InetAddress serverAddress=InetAddress.getByName(host);
try {
Socket clientSocket=new Socket(serverAddress,port);
BufferedOutputStream clientOutputBuffer = new BufferedOutputStream(clientSocket.getOutputStream());
OutputStreamWriter clientOutputStream = new OutputStreamWriter(clientOutputBuffer);
timeStamp=new Date().toString();
String clientMessage="Calling Server on "+host +" port" +port +" at" +timeStamp + (char)13;
clientOutputStream.write(clientMessage);
clientOutputStream.flush();
//BufferedInputStream clientInputBuffer= new BufferedInputStream(clientSocket.getInputStream());
//InputStreamReader clientInputStream = new InputStreamReader(clientInputBuffer);
int c;
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// while((c=clientInputStream.read())!=13){
// msgFromServer.append((char)c);
//}
FileOutputStream fos=new FileOutputStream("C:/Users/Sudhir/Desktop/sud.wmv");
BufferedOutputStream bos = new BufferedOutputStream(fos);
InputStream is = clientSocket.getInputStream();
int readbytes=is.read(clientBuffer,0,clientBuffer.length);
bos.write(clientBuffer,0,readbytes);
//System.out.println(msgFromServer);
//System.out.println("end");
bos.close();
clientSocket.close();
} catch (IOException e) {
System.out.println(e);
}
} catch (UnknownHostException e) {
System.out.println(e);
}
}
}
Related
I am creating a Server Client program which works before I try to implement multithreading on the server. I am unsure what is causing the issue. The client connects to the server, after selecting the upload or download option and sends the first line of the file, then the client crashes with this exception:
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at Client.upload(Client.java:66)
at Client.main(Client.java:99)
Client Code
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
public static void download(String filename)
{
try {
InetAddress host = InetAddress.getLocalHost();
Socket socket = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
socket = new Socket(host.getHostName(), 8001);
Writer out = new BufferedWriter(new OutputStreamWriter(new
FileOutputStream(filename),"utf8"));
oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject("Download");
oos.writeObject(filename);
oos.close();
socket.close();
while(true)
{
socket = new Socket(host.getHostName(), 8001);
oos = new ObjectOutputStream(socket.getOutputStream());
System.out.println("Line request sent");
oos.writeObject("Request");
ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
if(message.equalsIgnoreCase("%end%"))break;
out.write(message + "\n");
ois.close();
socket.close();
}
out.close();
oos.close();
}
catch(IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void upload(String filename)
{
try {
InetAddress host = InetAddress.getLocalHost();
Socket socket = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
BufferedReader in = new BufferedReader(new FileReader(filename));
socket = new Socket(host.getHostName(), 8001);
oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject("Upload");
oos.writeObject(filename);
oos.close();
socket.close();
String line = null;
while((line = in.readLine()) != null) {
socket = new Socket(host.getHostName(), 8001);
oos = new ObjectOutputStream(socket.getOutputStream());
System.out.println("Sending line to Socket Server");
oos.writeObject(line);
ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message: " + message);
ois.close();
oos.close();
Thread.sleep(100);
}
socket = new Socket(host.getHostName(), 8001);
oos = new ObjectOutputStream(socket.getOutputStream());
System.out.println("Sending end of file to Server");
oos.writeObject("%end%");
oos.close();
socket.close();
in.close();
}
catch(IOException | ClassNotFoundException | InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
int i = 0;
Scanner scanner = new Scanner(System.in);
do
{
System.out.println("Enter '-u' to upload or '-d' to download");
String input = scanner.next();
System.out.println("Enter the filename");
String filename = scanner.next();
if(input.equalsIgnoreCase("-u")) {
System.out.println("Uploading " + filename);
upload(filename);
i = 0;
}
else if(input.equalsIgnoreCase("-d")) {
System.out.println("Downloading " + filename);
download(filename);
i = 0;
}
else{
System.out.println("Invalid input try again");
i = 1;
}
}while(i == 1);
scanner.close();
}
}
Server Code before multithreading
import java.io.*;
import java.lang.ClassNotFoundException;
import java.net.*;
public class Server
{
private static ServerSocket server;
private static int port = 8001;
public static void upload(String fileName)
{
try {
System.out.println("File Uploading");
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName),
"utf-8"));
System.out.println("Created " + fileName);
while(true)
{
System.out.println("Waiting for next line");
Socket socket = server.accept();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
if(message.equalsIgnoreCase("%end%"))break;
out.write(message + "\n");
System.out.println("Message Received: " + message);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject("Server Received: " + message);
ois.close();
oos.close();
socket.close();
}
out.close();
System.out.println("Shutting down Socket server!!");
server.close();
}
catch(IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void download(String fileName)
{
try {
Socket socket = null;
System.out.println("Selected Download");
System.out.println(fileName + " Downloading");
BufferedReader in = new BufferedReader(new FileReader(fileName));
ObjectOutputStream oos = null;
String line = null;
while((line = in.readLine()) != null)
{
try
{
socket = server.accept();
oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(line);
System.out.println("Line " + line + " sent to client");
oos.close();
Thread.sleep(100);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println("Sending end of file");
Socket endSocket = server.accept();
ObjectOutputStream end = new ObjectOutputStream(endSocket.getOutputStream());
end.writeObject("%end%");
end.close();
in.close();
System.out.println("Shutting down Socket server!!");
server.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]) throws IOException, ClassNotFoundException
{
while(true)
{
try {
server = new ServerSocket(port);
System.out.println("Waiting for upload or download request from client");
Socket socketUpDown = server.accept();
ObjectInputStream request = new ObjectInputStream(socketUpDown.getInputStream());
String upDown = (String)request.readObject();
if(upDown.equals("Upload"))
{
upload((String)request.readObject());
}
else if(upDown.equals("Download"))
{
download((String)request.readObject());
}
socketUpDown.close();
}
catch(IOException | ClassNotFoundException e){
e.printStackTrace();
}
}
}
}
Server Code After Multithreading
import java.io.*;
import java.lang.ClassNotFoundException;
import java.net.*;
public class Server
{
private static ServerSocket server;
private static int port = 8001;
public static void main(String args[]) throws IOException, ClassNotFoundException
{
try
{
server = new ServerSocket(port);
int counter = 0;
System.out.println("Server Started ....");
while(true)
{
counter++;
Socket serverClient = server.accept();
System.out.println("A new client is connected : " + serverClient);
ServerClientThread sct = new ServerClientThread(serverClient, counter);
sct.start();
}
}catch(Exception e){
e.printStackTrace();
}
}
private static class ServerClientThread extends Thread
{
private int clientNo;
public ServerClientThread(Socket socket, int clientNo)
{
this.clientNo = clientNo;
}
public void run()
{
try {
System.out.println("Waiting for upload or download request from client");
Socket socketUpDown = server.accept();
ObjectInputStream request = new ObjectInputStream(socketUpDown.getInputStream());
String upDown = (String)request.readObject();
if(upDown.equals("Upload"))
{
upload((String)request.readObject());
}
else if(upDown.equals("Download"))
{
download((String)request.readObject());
}
socketUpDown.close();
}
catch(IOException | ClassNotFoundException e){
e.printStackTrace();
}
finally{
System.out.println("Client -" + clientNo + " exit!! ");
}
}
public static void upload(String fileName)
{
try {
System.out.println("File Uploading");
Writer out = new BufferedWriter(new OutputStreamWriter(new
FileOutputStream(fileName), "utf-8"));
System.out.println("Created " + fileName);
while(true)
{
System.out.println("Waiting for next line");
Socket socket = server.accept();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
if(message.equalsIgnoreCase("%end%"))break;
out.write(message + "\n");
System.out.println("Message Received: " + message);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject("Received" + message);
ois.close();
oos.close();
socket.close();
}
out.close();
System.out.println("Shutting down Socket server!!");
server.close();
}
catch(IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void download(String fileName)
{
try {
Socket socket = null;
System.out.println("Selected Download");
System.out.println(fileName + " Downloading");
BufferedReader in = new BufferedReader(new FileReader(fileName));
ObjectOutputStream oos = null;
String line = null;
while((line = in.readLine()) != null)
{
try{
socket = server.accept();
oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(line);
System.out.println("Line " + line + " written to file");
oos.close();
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Sending end of file");
Socket endSocket = server.accept();
ObjectOutputStream end = new ObjectOutputStream(endSocket.getOutputStream());
end.writeObject("%end%");
end.close();
in.close();
System.out.println("Shutting down Socket server!!");
server.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
}
I wrote a Java server application that returns a file when it is requested by a browser. The browser makes a GET request to my socket and the socket returns the file. But the browser (firefox in my case) treats the html file as a regular text file and does not render the actual page. So the browser shows the whole html source code. How can I fix that?
Here the Code:
package ml.mindlabor.networking;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
static final int PORT = 9806;
static final int MAX_BYTES_PER_STREAM = 10_000; // 10 kB
static final String FILE_SYSTEM_PATH = "C:\\Users\\SBrau\\eclipse-workspace\\Networking\\src\\ml\\mindlabor\\networking\\Files\\public_html";
static boolean running = true;
ServerSocket ss = null;
Socket soc = null;
public static void main(String[] args) {
Server server = new Server();
// When the connection could not be established
System.out.println("Waiting for connection ...");
if (!server.connect()) return;
server.listenForResponse();
}
public Server() {
try {
ss = new ServerSocket(PORT);
} catch (IOException e) {
System.err.println("Could not create ServerSocket on Port " + PORT);
shutdown();
}
}
boolean respond(String response) {
try {
PrintWriter out = new PrintWriter(soc.getOutputStream(), true);
out.println(response);
return true;
} catch (IOException e) {
System.err.println("Could not send to Port " + PORT);
}
return false;
}
boolean respond(byte[] response) {
try {
soc.getOutputStream().write(response);
return true;
} catch (IOException e) {
System.err.println("Could not send to Port " + PORT);
}
return false;
}
boolean respondFile(String relPath) {
String path = Server.FILE_SYSTEM_PATH + relPath;
File file = new File(path);
try {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[(int)file.length()]; // or 4096, or more
in.read(buffer, 0, buffer.length);
soc.getOutputStream().write(buffer, 0, buffer.length);
System.out.println("Loaded :D");
in.close();
soc.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
String rawDataToString(byte[] rawData) {
return new String(rawData);
}
void listenForResponse() {
new Thread(() -> {
while (true) {
try {
DataInputStream in = new DataInputStream(soc.getInputStream());
byte[] packetData = new byte[MAX_BYTES_PER_STREAM];
in.read(packetData);
receivedPackage(packetData);
} catch (IOException e) {
System.err.println("Could not get data from port " + PORT);
shutdown();
}
}
}).start();
}
void shutdown() {
Server.running = false;
}
void receivedPackage(byte[] pkg) {
String request = new String(pkg).trim();
// GET Request for file
if (request.contains("GET ")) {
String[] arr = request.split(" ");
respondFile(arr[1].trim());
}
}
boolean connect() {
try {
soc = ss.accept();
//soc.setKeepAlive(true);
System.out.println("Connected!");
return true;
} catch (IOException e) {
System.err.println("Could not wait for connection on port " + PORT);
shutdown();
}
return false;
}
}
Ok. Got it. I solved it by rewriting the following method:
boolean respondFile(String relPath) {
String path = Server.FILE_SYSTEM_PATH + relPath;
File file = new File(path);
try {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
PrintWriter out = new PrintWriter(soc.getOutputStream());
BufferedOutputStream dataOut = new BufferedOutputStream(soc.getOutputStream());
byte[] fileData = readFileData(file, (int)file.length());
out.println("HTTP/1.1 501 Not Implemented");
out.println("Content-type: text/html");
out.println(); // blank line between headers and content, very important !
out.flush();
dataOut.write(fileData, 0, fileData.length);
dataOut.flush();
System.out.println("Loaded :D");
in.close();
soc.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
private byte[] readFileData(File file, int fileLength) throws IOException {
FileInputStream fileIn = null;
byte[] fileData = new byte[fileLength];
try {
fileIn = new FileInputStream(file);
fileIn.read(fileData);
} finally {
if (fileIn != null)
fileIn.close();
}
return fileData;
}
I need to transfer few files to different computers, 1 file per 1 computer. Now i can only transfer 1 file to 1 computer. Also some computers from my IP pool can be offline, how can i avoid Exception?
Also I have all code in github:
https://github.com/xym4uk/Diplom/tree/master/src/xym4uk/test
Client
package xym4uk.test;
import java.io.*;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class FileClient {
private static Socket sock;
private static String fileName;
private static BufferedReader stdin;
private static PrintStream ps;
public static void main(String[] args) throws IOException {
public static void sendFile(File myFile) {
//connecting
try {
sock = new Socket("localhost", 4444);
ps = new PrintStream(sock.getOutputStream());
ps.println("1");
} catch (Exception e) {
System.err.println("Cannot connect to the server, try again later.");
System.exit(1);
}
try {
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 = sock.getOutputStream();
//Sending file name and file size to the server
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
dos.write(mybytearray, 0, mybytearray.length);
dos.flush();
System.out.println("File " + myFile.getName() + " sent to Server.");
} catch (Exception e) {
System.err.println("File does not exist!");
}
DataBase.setRecord(sock.getInetAddress().toString(), myFile.getName());
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void receiveFile(String fileName) {
try {
sock = new Socket("localhost", 4444);
ps = new PrintStream(sock.getOutputStream());
ps.println("2");
ps.println(fileName);
} catch (Exception e) {
System.err.println("Cannot connect to the server, try again later.");
System.exit(1);
}
try {
int bytesRead;
InputStream in = sock.getInputStream();
DataInputStream clientData = new DataInputStream(in);
fileName = clientData.readUTF();
OutputStream output = new FileOutputStream(("received_from_server_" + 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.close();
in.close();
System.out.println("File " + fileName + " received from Server.");
} catch (IOException ex) {
Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
}
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server
package xym4uk.test;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer {
private static ServerSocket serverSocket;
private static Socket clientSocket = null;
public static void main(String[] args) throws IOException {
try {
serverSocket = new ServerSocket(4444);
System.out.println("Server started.");
} catch (Exception e) {
System.err.println("Port already in use.");
System.exit(1);
}
while (true) {
try {
clientSocket = serverSocket.accept();
System.out.println("Accepted connection : " + clientSocket.getInetAddress());
Thread t = new Thread(new CLIENTConnection(clientSocket));
t.start();
} catch (Exception e) {
System.err.println("Error in connection attempt.");
}
}
}
}
ClientConnection
package xym4uk.test;
import java.io.*;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class CLIENTConnection implements Runnable {
private Socket clientSocket;
private BufferedReader in = null;
public CLIENTConnection(Socket client) {
this.clientSocket = client;
}
#Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String clientSelection;
while ((clientSelection = in.readLine()) != null) {
switch (clientSelection) {
case "1":
receiveFile();
break;
case "2":
String outGoingFileName;
while ((outGoingFileName = in.readLine()) != null) {
sendFile(outGoingFileName);
}
break;
default:
System.out.println("Incorrect command received.");
break;
}
in.close();
break;
}
} catch (IOException ex) {
Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void receiveFile() {
try {
int bytesRead;
DataInputStream clientData = new DataInputStream(clientSocket.getInputStream());
String fileName = clientData.readUTF();
OutputStream output = new FileOutputStream(("received_from_client_" + 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.close();
clientData.close();
System.out.println("File "+fileName+" received from client.");
} catch (IOException ex) {
System.err.println("Client error. Connection closed.");
}
}
public void sendFile(String fileName) {
try {
//handle file read
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);
//handle file send over socket
OutputStream os = clientSocket.getOutputStream();
//Sending file name and file size to the client
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
dos.write(mybytearray, 0, mybytearray.length);
dos.flush();
System.out.println("File "+fileName+" sent to client.");
} catch (Exception e) {
System.err.println("File does not exist!");
}
}
}
i am coding a multi client chat server.i have a server folder that contains Server.java and three client folders namely client1,client2,client3 containing java files resp.now when every client joins the server i try to send a text but the server does not picks the message.the problem is in the void run() try method. till the while(true) loop everything works.
Server code:
Chat.java
import java.net.*;
import java.io.*;
import java.util.*;
class Chat implements Runnable {
Socket skt = null;
DataInputStream dis = null;
DataOutputStream dos = null;
PrintWriter pw = null;
TreeMap<Socket, String> tm;
public Chat(Socket skt, TreeMap<Socket, String> tm) {
this.skt = skt;
this.tm = tm;
}
public void run() {
try {
dis = new DataInputStream(skt.getInputStream());
String msg = "";
while (true) {
msg = dis.readUTF();
Set s = tm.keySet();
Iterator itr = s.iterator();
while (itr.hasNext()) {
String k = (String) itr.next();
Socket v = (Socket) tm.get(k);
dos = new DataOutputStream(v.getOutputStream());
dos.writeUTF();
}
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
dis.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
Server.java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.TreeMap;
class Server
{
public static void main(String dt[])
{
ServerSocket sskt=null;
Socket skt=null;
DataInputStream dis=null;
DataOutputStream dos=null;
TreeMap <String,Socket>tm=new TreeMap<String,Socket>();
try
{
sskt=new ServerSocket(1234);
System.out.println("Waiting for Clients");
while(true)
{
skt=sskt.accept();
dis=new DataInputStream(skt.getInputStream());
dos=new DataOutputStream(skt.getOutputStream());
String user=dis.readUTF();
String pass=dis.readUTF();
if(user.equals(pass))
{
dos.writeBoolean(true);
tm.put(user,skt);
Chat ch=new Chat(skt,tm);
Thread t=new Thread(ch);
t.start();
}
else
{
dos.writeBoolean(false);
}
} //end of while.
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
try
{
dos.close();
dis.close();
skt.close();
sskt.close();
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
}
Client Code:
Send.java
import java.io.*;
import java.net.*;
class Send implements Runnable {
Socket skt = null;
public Send(Socket skt) {
this.skt = skt;
System.out.println(skt);
}
public void run() {
InputStreamReader isrout = null;
BufferedReader brout = null;
PrintWriter pw = null;
DataInputStream dis = null;
try {
// Thread.sleep(2000);
System.out.println("Send a text");
isrout = new InputStreamReader(System.in);
brout = new BufferedReader(isrout);
pw = new PrintWriter(skt.getOutputStream(), true);
do {
String msg = brout.readLine();
pw.println(msg);
} while (!msg.equals("bye"));
} catch (Exception e) {
System.out.println(e);
} finally {
try {
pw.close();
brout.close();
isrout.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
Client1.java
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
class Client1 {
public static void main(String dt[]) {
Socket skt = null;
InputStreamReader isr = null;
BufferedReader br = null;
DataOutputStream dos = null;
DataInputStream dis = null;
try {
skt = new Socket("127.0.0.1", 1234);
System.out.println("Connected to server");
System.out.println(skt);
isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
dos = new DataOutputStream(skt.getOutputStream());
dis = new DataInputStream(skt.getInputStream());
System.out.println("Enter a username");
String user = br.readLine();
dos.writeUTF(user);
System.out.println("Enter a password");
String pass = br.readLine();
dos.writeUTF(pass);
if (dis.readBoolean()) {
System.out.println("User Authenticated");
} else {
System.out.println("Incorrect username or password");
}
Send sn = new Send(skt);
Thread t = new Thread(sn);
t.start();
} catch (Exception e) {
System.out.println(e);
} finally {
try {
// skt.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
After writing any value using an outputstream you need to flush it to actually send it.
In the Chat and Server class where you use DataOutputStream, you need to call this after writing data.
dos.flush();
In the Client class after sending data through the PrintWriter you need to call this.
pw.flush();
I've tried to write a server and a client in java, to transfer a file. but the received file is weird and look like it's filled with strange bytes and it won't open with any application, however its size is exactly same as the source file.
I don't know where the problem is! is it about encoding?
Server-side:
import java.net.*;
import java.io.*;
public class MyServer {
public static void main(String[] args) {
char sp = File.separatorChar;
String home = System.getProperty("user.home");
try {
ServerSocket server = new ServerSocket(5776);
while (true){
Socket connection = server.accept();
try {
String FileName=home+sp+"33.jpg";
File inputFile = new File(FileName);
FileInputStream Fin = new FileInputStream(inputFile);
long fileLength = inputFile.length();
byte[] bt= new byte[(int) fileLength];
DataOutputStream Oout = new DataOutputStream(connection.getOutputStream());
Oout.writeLong(fileLength);
Oout.write(bt);
Oout.flush();
Oout.close();
connection.close();
} catch (IOException ex) {}
finally {
try {
if(connection!= null) connection.close();
} catch (IOException e) {}
}
}
} catch (IOException e) {
System.err.println("There is a server on port 5776");
}
}
}
Client-side:
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) {
byte[] IP={(byte)192,(byte)168,1,7};
char sp = File.separatorChar;
String home = System.getProperty("user.home");
String SharingPathString = home+sp+"File Sharing";
String FileName = SharingPathString+sp+"file.jpg";
try {
InetAddress add = InetAddress.getByAddress(IP);
Socket theSocket= new Socket("Shayan-8",5776);
DataInputStream in= new DataInputStream(theSocket.getInputStream());
final long FileLength = in.readLong();
System.out.println("FileLength: "+FileLength);
File SharingPath = new File(SharingPathString);
if(!SharingPath.exists())
SharingPath.mkdir();
File outputFile = new File(FileName);
if(outputFile.exists())
outputFile.delete();
//outputFile.createNewFile();
FileOutputStream Fos = new FileOutputStream(FileName);
DataOutputStream dos = new DataOutputStream(Fos);
byte[] buffer = new byte[100];
int count=0;
long current=0;
while(current < FileLength && (count=in.read(buffer,0,(int)Math.min(FileLength-current, buffer.length)))!=-1)
{Fos.write(buffer, 0, count);
current+=count;
}
// while((count=in.read())!=-1)
// dos.write(count);
dos.close();
Fos.close();
} catch (UnknownHostException uhe) {
System.err.println(uhe);
} catch (IOException e) {
System.err.println(e);
}
}
}
You haven't read anything into bt[]. So you are writing the correct number of null bytes.