I want to send file from client to server using socket.
But at the server, I only receive the first line. What is the problem?
Server Code
public static void main(String ars[]){
int port = 1000;
try {
ServerSocket sercoc = new ServerSocket(port);
System.out.println("dkjd");
while (true){
Socket soc = sercoc.accept();
InputStream flux = soc.getInputStream();
BufferedReader entree = new BufferedReader(new InputStreamReader(flux));
String message = entree.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Client Code
public static void main(String args[]){
String hote = "127.00.0.1";
int port = 1000;
FileReader input = null;
File file = new File("src/view/files/temperature2.txt");
Socket soc = null;
try {
soc = new Socket(hote,port);
OutputStream flux = soc.getOutputStream();
OutputStreamWriter sortie = new OutputStreamWriter(flux);
try {
input = new FileReader("src/view/files/temperature2.txt");
char c;
while ((c = (char) input.read()) != -1){
sortie.write(c);
//sortie.write("\n");
}
} finally {
if (input != null){
input.close();
}
}
sortie.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
If I use BufferedReader I found errors and I can't receive anything!
in my code I have implemented the transfer of photo, txt and zip files through ObjectOutputStream and ObjectInputStream.
code:
// output
ObjectOutputStream objectOutput = new ObjectOutputStream(connection.clientSocket.getOutputStream());
objectOutput.writeObject(your_file);
// input
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
buffer = (byte[]) ois.readObject();
Related
hi guys i tried to send txt through socket it worked using the following source code but i got an exception when i want to send the zip files.Any help will be appreciated thanks
Java server
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub}
sendFile("FileTest.rar");
}
public static Boolean sendFile(String strFileToSend) {
try {
ServerSocket serverSocket = new ServerSocket(1592);
Socket socket = serverSocket.accept();
System.out.println("Connection accepted from " + socket);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
File file = new File(strFileToSend);
// send file length
out.println(file.length());
// read file to buffer
byte[] buffer = new byte[(int) file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.read(buffer, 0, buffer.length);
// send file
BufferedOutputStream bos = new BufferedOutputStream(
socket.getOutputStream());
bos.write(buffer);
bos.flush();
// added
dis.close();
serverSocket.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
C# client
public static bool receiveFile(string ip,string strFilePath)
{
try
{
TcpClient tcpClient = new TcpClient();
tcpClient.Connect(ip, 1592);
NetworkStream networkStream = tcpClient.GetStream();
StreamReader sr = new StreamReader(networkStream);
//read file length
int length = int.Parse(sr.ReadLine());
//read bytes to buffer
byte[] buffer = new byte[length];
networkStream.Read(buffer, 0, (int)length);
//write to file
BinaryWriter bWrite = new BinaryWriter(File.Open(strFilePath, FileMode.Create));
bWrite.Write(buffer);
bWrite.Flush();
bWrite.Close();
return true;
}
catch(Exception exException)
{
MessageBox.Show(exException.Message);
return false;
}
}
The problem is when i want to deal with rar or zip files.
Thanks in advance
i got the exeption below.It occurs at this line in the client app
int length = int.Parse(sr.ReadLine());
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();
}
}
I'm trying to develop a client-server exchange program, and when I try to send data from client to server, I'm running into a SocketException. I've looked at other answers but none of them fit my exact case; I have two calls to osw.write, and only one of them works.
Client:
package me.primesearch.client;
import java.math.BigInteger;
import java.net.*;
import java.io.*;
public class PrimeSearchClient {
public static void main(String[] args) throws IOException{
Socket connection = null;
try{
/** Define a host server */
String host = "localhost";
/** Define a port */
int port = 25564;
StringBuffer instr = new StringBuffer();
System.out.println("SocketClient initialized");
/** Obtain an address object of the server */
InetAddress address = InetAddress.getByName(host);
/** Establish a socket connetion */
connection = new Socket(address, port);
/** Instantiate a BufferedOutputStream object */
BufferedOutputStream bos = new BufferedOutputStream(connection.
getOutputStream());
/** Instantiate a BufferedInputStream object for reading
/** Instantiate a BufferedInputStream object for reading
* incoming socket streams.
*/
BufferedInputStream bis = new BufferedInputStream(connection.
getInputStream());
/**Instantiate an InputStreamReader with the optional
* character encoding.
*/
InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");
/**Read the socket's InputStream and append to a StringBuffer */
int c;
/** Instantiate an OutputStreamWriter object with the optional character
* encoding.
*/
OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
while(true){
String process = "drq " + (char) 13;
/** Write across the socket connection and flush the buffer */
osw.write(process);
osw.flush();
while ( (c = isr.read()) != 13)
instr.append( (char) c);
for(int i=0;i<50;i++){
BigInteger offset=new BigInteger(instr.toString()).add(BigInteger.valueOf(i));
if(isProbablyPrime(offset)){
process = "pri" + " " + offset + " " + (offset.divide(new BigInteger("50"))).toString() + (char) 13;
System.out.println(process);
/** Write across the socket connection and flush the buffer */
osw.write(process); //This doesn't work
osw.flush();
System.out.println("Prime found at " + offset);
}
}
}
} catch(IOException e) {
e.printStackTrace();
} finally {
connection.close();
}
}
public static boolean isProbablyPrime(BigInteger n) {
if(n.longValue()!=0){
BigInteger lessOne = n.subtract(BigInteger.ONE);
// get the next prime from one less than number and check with the number
return lessOne.nextProbablePrime().compareTo(n) == 0;
}
return false;
}
}
Server:
package me.primesearch.server;
import java.net.*;
import java.io.*;
public class PrimeSearchServer implements Runnable {
private Socket connection;
#SuppressWarnings("unused")
private int ID;
PrimeSearchServer(Socket s, int i) {
this.connection = s;
this.ID = i;
}
#SuppressWarnings("resource")
public static void main(String[] args) {
int port = 25564;
int count = 0;
try{
ServerSocket socket1 = new ServerSocket(port);
System.out.println("MultipleSocketServer Initialized");
while (true) {
Socket connection = socket1.accept();
Runnable runnable = new PrimeSearchServer(connection, ++count);
Thread thread = new Thread(runnable);
thread.start();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void run() {
try {
BufferedInputStream is = new BufferedInputStream(connection.getInputStream());
InputStreamReader isr = new InputStreamReader(is);
int character;
StringBuffer process = new StringBuffer();
while((character = isr.read()) != 13) {
process.append((char)character);
}
System.out.println(process);
String returnCode="0";
if(process.toString().split(" ")[0].equals("drq")){
System.out.println("Job request recieved");
File file = new File("packages.txt");
//Process input
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
String prevLine="";
boolean i = false;
int count=0;
while ((line = br.readLine()) != null) {
System.out.println("Looking for a package to send");
// process the line.
if(line.equals("0")){
System.out.println("Sending package " + count);
returnCode = Integer.toString(count);
i = true;
break;
}
prevLine = line;
count++;
System.out.println("No packages found");
}
if(!i){
returnCode = prevLine;
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("packages.txt", true)))) {
System.out.println("Creating new package");
out.println("0");
returnCode=Integer.toString(count);
}catch (IOException e) {
e.printStackTrace();
}
}
}
} else if (process.toString().split(" ")[0].equals("pri")){
System.out.println("Prime request recieved");
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("primes.txt", true)))) {
out.println(Integer.parseInt(process.toString().split(" ")[1]));
}catch (IOException e) {
e.printStackTrace();
}
updateLine(Integer.parseInt(process.toString().split(" ")[2]));
}
BufferedOutputStream os = new BufferedOutputStream(connection.getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(os, "US-ASCII");
osw.write(returnCode + (char)13);
osw.flush();
process = new StringBuffer();
}
catch (Exception e) {
System.out.println(e);
}
finally {
try {
connection.close();
}
catch (IOException e){
e.printStackTrace();
}
}
}
private void updateLine(int lines) throws IOException {
String data="packages.txt";
BufferedReader file = new BufferedReader(new FileReader(data));
String input = "";
String line;
for(int i=0;i<lines;i++){
input+=file.readLine()+System.lineSeparator();
}
file.readLine();
while ((line = file.readLine()) != null)
input += line + System.lineSeparator();
FileOutputStream os = new FileOutputStream(data);
os.write(input.getBytes());
file.close();
os.close();
}
}
Sorry if the indenting on the code looks a bit strange, I'm not used to using stack overflow.
You are closing the socket in your server class:
finally {
try {
connection.close();
}
catch (IOException e){
e.printStackTrace();
}
}
I think this is the problem. This is the first message you're sending to the server.
Client
String process = "drq " + (char) 13;
osw.write(process);
osw.flush();
And since your server stops reading after it gets a 13 char it closes the connection after it reads the first message.
Server
while((character = isr.read()) != 13) {
process.append((char)character);
}
I was getting the same exception when running functional test using TestNG. For me it was a version issue. Uninstalling it and installing older version fixed my issue. Read the following post for information.
https://github.com/cbeust/testng-eclipse/issues/91
I've been trying to fix this error for days now. Really. I just don't get it. The code is simple enough.. Why is it not working?
public class server
{
public static void main(String[] args)
{
String fileName = null;
try
{
ServerSocket ss = new ServerSocket(9999, 3);
Socket dataSocket = ss.accept();
System.out.println("Server: Connection Established");
InputStream is = dataSocket.getInputStream();
//BufferedReader br = new BufferedReader(new InputStreamReader(is));
Scanner sc = new Scanner(dataSocket.getInputStream());
while(sc.hasNextByte())
{
System.out.println("True");
fileName = fileName+sc.next();
}
FileWriter fw = new FileWriter("server"+fileName);
while(dataSocket != null)
{
fw.write(is.read());
}
fw.flush();
dataSocket.close();
ss.close();
/*String[] nameParts;
nameParts = fileName.split(".");
File f = new File(nameParts[0]+"."+nameParts[1]);
FileOutputStream fos = new FileOutputStream(f);
System.out.println(nameParts[0]);*/
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Above is the server code. The client code is below:
public class client
{
public static void main(String[] args)
{
// Read a file
try
{
Socket dataSocket = new Socket();
dataSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(), 9999));
System.out.println("Client: Connection Established");
OutputStream os = dataSocket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
String fileName = "text.txt";
pw.write(fileName);
File f = new File(fileName);
Scanner sc = new Scanner(f);
/*while(sc.hasNextInt())
{
pw.write(sc.nextInt());
}*/
//pw.flush();
//pw.close();
//dataSocket.close();
/*String[] nameParts = new String[2];
nameParts = args[0].split(".");
while(sc.hasNextByte())
{
os.write(sc.nextByte());5
}*/
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
At first, both client and server just kept waiting for each other to speak, like two shy teenagers. After a few changes, this started to happen. I get the Connection Reset error. Please help. Deadlines!
sc.hasNextByte() remains true until the peer has closed the connection. So you will never get out of this loop. You need to send the filename length ahead of the filename, so you know how much of the incoming data is the filename. Then read the filename, open the file, and read and copy the rest of the stream until EOS.
Optionally, you can write your file name with a lien as below:
pw.write(fileName + "\n");
Or user some writer to writeLine(fileName ).
And in server side, use bufferedReader to read line by line:
while ((line = br.readLine()) != null) {
....
}
Then it can finish the loop if the client is closed.
I have a problem with printing on this specific printer.
public void print(String fileName, String printerIp) {
try {
BufferedReader streamIn = new BufferedReader(new FileReader(fileName));
String line;
Socket socket = new Socket(printerIp, 9100);
Writer writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
while ((line = streamIn.readLine()) != null) {
writer.write(line);
}
writer.flush();
socket.close();
streamIn.close();
}
The situation looks like everything is fine but the printer do not print, when I use other program to print everything works fine.
Any thoughts ?
The solution is to write whole file to the printer.
public void printFile(File file, String printerIp) throws PrintException, IOException {
Socket socket = new Socket(printerIp, 9100);
FileInputStream fileInputStream = new FileInputStream(file);
byte [] mybytearray = new byte [(int)file.length()];
fileInputStream.read(mybytearray,0,mybytearray.length);
OutputStream outputStream = socket.getOutputStream();
outputStream.write(mybytearray,0,mybytearray.length);
//Curious thing is that we have to wait some time to make more prints.
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
outputStream.flush();
outputStream.close();
socket.close();
fileInputStream.close();
}