473,624 Members | 2,223 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Need Desperate Help...Java Sockets

hi Everyone
I am trying to create a server and client to send files from one side
to the other. I can send files from one side to the other using
bufferedinput/output streams but when trying to send normal messages
with printwriter my files being sent across are messed up. Empty jpg's
are being sent with wrong file sizes. My code as follows:
public class TCPServer
{
public static final int BUFFER_SIZE = 4096;
public static final int RCV_PORT = 45000;

public static void main(String[] args)
{
ServerSocket server;
Socket socket;
File file;
PrintWriter out;
BufferedReader in;
String line;

file = new File("C:Project ");

try
{
server = new ServerSocket(RC V_PORT);
socket = server.accept() ;

OutputStream os = socket.getOutpu tStream();
InputStream is = socket.getInput Stream();
out = new PrintWriter(os, true);
in = new BufferedReader( new InputStreamRead er(is));

out.println("OK "); //WHEN I HAVE THIS LINE MY FILE BEING SEND IT
MESSED UP. BUT WITHOUT THIS THE FILE IS SENT PERFECTLY
SendFile(file, "test.JPG", os);
out.close();
in.close();
socket.close();
} catch (IOException e) { }

}

static void SendFile(File file, String filename, OutputStream os)
{
try
{
byte[] buffer = new byte[BUFFER_SIZE];
int count;
File nfile = new File(file,filen ame);
FileInputStream Fis = new FileInputStream (nfile);
BufferedInputSt ream ins = new BufferedInputSt ream(Fis);
BufferedOutputS tream outs = new BufferedOutputS tream(os);
while(true)
{
count = ins.read(buffer , 0, BUFFER_SIZE);
if (count <= 0)
break;
outs.write(buff er, 0, count);
System.out.prin tln(buffer);
}
outs.flush();
outs.close();
ins.close();
} catch (IOException e) {System.out.pri ntln(e);}
}

}

CLIENT
---------

public class TCPClient
{
public static final int BUFFER_SIZE = 4096;
public static final String FILE_NAME = "WORK.jpg";
public static void main(String[] args)
{
int port;
String addr;
try
{
Socket socket = new Socket(addr,por t);
OutputStream os = socket.getOutpu tStream();
InputStream is = socket.getInput Stream();
PrintWriter out = new PrintWriter(os, true);
BufferedReader in = new BufferedReader( new InputStreamRead er(is));

String line = in.readLine(); //WHEN I HAVE THIS CODE ON THE CLIENT
SIDE
if (line.compareTo ("OK")!=0) //WITH RESPECT TO WHAT I HAVE ON THE
SERVER SIDE
return; //THE FILE BEING RECEIVED IS MESSED UP, OTHERWISE IS PERFECTLY
RECEIVED

RcvFile(is);

out.close();
in.close();
socket.close();
} catch (IOException e) { }

}

static void RcvFile(InputSt ream is)
{
try
{
BufferedInputSt ream ins = new BufferedInputSt ream(is);
BufferedOutputS tream outs = new BufferedOutputS tream(new
FileOutputStrea m(FILE_NAME));
byte[] buffer = new byte[BUFFER_SIZE];

while(true)
{
int count = ins.read(buffer , 0, BUFFER_SIZE);
if (count <= 0)
{
break;
}
outs.write(buff er, 0, count);
System.out.prin tln(buffer);
}
outs.flush();
ins.close();
outs.close();
}
catch(IOExcepti on e) {}
}

}


Please let me know what i am doing wrong. From all the playing around
i have done it seems that once i bind and send anything via the
printwriter the Bufferedinputst ream doesn't work properly.

Thanks a million

JatP
Jul 17 '05 #1
1 3309
Did you look at the line separator on client and server side?
The documentation of PrintWriter says

* The println() methods
* use the platform's own notion of line separator rather than the newline
* character.

See also the private void newLine() method in PrintWriter.

Stephan

_______________ _______________ ____________
Stephan Wehner
Editor, Traffic Life: Passionate Tales and Exit Strategies
An anthology about our car culture and alternatives with
short stories, poems, cartoons and lots of other art
www.trafficlife.com

vi********@yaho o.com (JatP) wrote in message news:<8e******* *************** ****@posting.go ogle.com>...
hi Everyone
I am trying to create a server and client to send files from one side
to the other. I can send files from one side to the other using
bufferedinput/output streams but when trying to send normal messages
with printwriter my files being sent across are messed up. Empty jpg's
are being sent with wrong file sizes. My code as follows:
public class TCPServer
{
public static final int BUFFER_SIZE = 4096;
public static final int RCV_PORT = 45000;

public static void main(String[] args)
{
ServerSocket server;
Socket socket;
File file;
PrintWriter out;
BufferedReader in;
String line;

file = new File("C:Project ");

try
{
server = new ServerSocket(RC V_PORT);
socket = server.accept() ;

OutputStream os = socket.getOutpu tStream();
InputStream is = socket.getInput Stream();
out = new PrintWriter(os, true);
in = new BufferedReader( new InputStreamRead er(is));

out.println("OK "); //WHEN I HAVE THIS LINE MY FILE BEING SEND IT
MESSED UP. BUT WITHOUT THIS THE FILE IS SENT PERFECTLY
SendFile(file, "test.JPG", os);
out.close();
in.close();
socket.close();
} catch (IOException e) { }

}

static void SendFile(File file, String filename, OutputStream os)
{
try
{
byte[] buffer = new byte[BUFFER_SIZE];
int count;
File nfile = new File(file,filen ame);
FileInputStream Fis = new FileInputStream (nfile);
BufferedInputSt ream ins = new BufferedInputSt ream(Fis);
BufferedOutputS tream outs = new BufferedOutputS tream(os);
while(true)
{
count = ins.read(buffer , 0, BUFFER_SIZE);
if (count <= 0)
break;
outs.write(buff er, 0, count);
System.out.prin tln(buffer);
}
outs.flush();
outs.close();
ins.close();
} catch (IOException e) {System.out.pri ntln(e);}
}

}

CLIENT
---------

public class TCPClient
{
public static final int BUFFER_SIZE = 4096;
public static final String FILE_NAME = "WORK.jpg";
public static void main(String[] args)
{
int port;
String addr;
try
{
Socket socket = new Socket(addr,por t);
OutputStream os = socket.getOutpu tStream();
InputStream is = socket.getInput Stream();
PrintWriter out = new PrintWriter(os, true);
BufferedReader in = new BufferedReader( new InputStreamRead er(is));

String line = in.readLine(); //WHEN I HAVE THIS CODE ON THE CLIENT
SIDE
if (line.compareTo ("OK")!=0) //WITH RESPECT TO WHAT I HAVE ON THE
SERVER SIDE
return; //THE FILE BEING RECEIVED IS MESSED UP, OTHERWISE IS PERFECTLY
RECEIVED

RcvFile(is);

out.close();
in.close();
socket.close();
} catch (IOException e) { }

}

static void RcvFile(InputSt ream is)
{
try
{
BufferedInputSt ream ins = new BufferedInputSt ream(is);
BufferedOutputS tream outs = new BufferedOutputS tream(new
FileOutputStrea m(FILE_NAME));
byte[] buffer = new byte[BUFFER_SIZE];

while(true)
{
int count = ins.read(buffer , 0, BUFFER_SIZE);
if (count <= 0)
{
break;
}
outs.write(buff er, 0, count);
System.out.prin tln(buffer);
}
outs.flush();
ins.close();
outs.close();
}
catch(IOExcepti on e) {}
}

}


Please let me know what i am doing wrong. From all the playing around
i have done it seems that once i bind and send anything via the
printwriter the Bufferedinputst ream doesn't work properly.

Thanks a million

JatP

Jul 17 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
3935
by: Jochen Daum | last post by:
Hi, I have to emulate a "file upload" to a Java Servlet which is done with the class URLConnection. The java source basically does URLConnection conn = theurl.openConnection("https://somesite"); w = conn.getOutputStream(); w.write(...)
9
4026
by: | last post by:
Java has packages (libraries) for everything. EVERYTHING. Instead, C++ is too poor in its classes. Is there a concept to extend C++ with other standard libraries, about multithreading, socket programming etc? I do not speak about libraries programmed only in one platform (e.g. MFC) but about standard C++ libraries.
3
14860
by: Jay | last post by:
Hi, I implemeneted an FTP client and server long time back using Java. I found sockets porgramming in java quite useful and easy to handle. I now wanted to implement a similar program using C++. My questions are 1. How good a language is C++ for network programming? 2. what are good onine resources to learn C++ network programming? 3. How similar it is to Java socket programming? Thanks in advance.
31
2577
by: somebody | last post by:
No, I'm not a troll, just angry. I just started learning C++, and find it extremely lacking compared to Java. For example, I had to write my own functions to do something as simple as a case insensitive string comparison, and a substring search. Then I found that there are no networking classes to speak of (except sockets). After I thought about it, C++ really pales by comparison. Java has a rich set of networking classes, regular...
23
2528
by: vinod.bhavnani | last post by:
Hello all, I need desperate help Here is the problem: My problem today is with multidimensional arrays. Lets say i have an array A this is a 4 dimensional static array.
4
6657
by: jediknight | last post by:
Hi, I am trying to establish whether I can have a C# socket server and Java socket clients. From all the examples I have seen on the web refer to Java Servers and C# clients. Can anyone point me in the direction of a C# socket server and Java client example?? Cheers
3
2392
by: Dameon99 | last post by:
Hi.. Im experiencing a weird error I dont know how to fix. I have a scanner object and whenever I use nextInt, anything above 3 causes the program to crash saying and links me to this line of the class: (one I added all the asteriss to. // If we are at the end of input then NoSuchElement; // If there is still input left then InputMismatch private void throwFor() { skipped = false; if ((sourceClosed) &&...
0
1219
by: yjh0914 | last post by:
hi guys! so im basically editting my post i made earlier as it wznt as specific.. i have to make a program that basically ranks students by their cumulative gpa. the student's info is on a csv file written in a format like this, "name,bday,sex,9-1,9-2,10-1,10-2.....,cumulative". my question is, should i read this whole line nd jz use the cumulative data (im not sure how to do dat:/) or make a separate class nd make an array (for loop nd stuff)...
1
1241
by: brendanmcdonagh | last post by:
Hi all, I have my little message program working until i press a button and then it'll go to actionPerformed method, and stop reading but will keep sending a message which is being received. Obviously, this is because the send is in the actionperformed method but the read is in the main method. Anyone offer any solutions to getting my program reading again after actionmethod() has been called. I ve tried to just create a method for read which...
4
1256
by: kingmathyou | last post by:
I have been trying to figure it out this program for the passed two hours with no luck. It is probably very easy, but I can't figure it out. Here is what I have to do: Write a program that asks the user to enter name and score of students via a dialog box. Output the number of students, their names, and if their grade is above (or equal to) the average scores. • User may enter information about any number of students. • The user must...
0
8238
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8680
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8478
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7164
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6111
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5565
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4082
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
1786
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1485
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.