Reading / Writing files using Sockets
Hi there guys,
I am fairly new to this forum. I have been having a problem for the past three days. I am implementing a client/server implementation using Sockets which is a submodule of a project I am working on. What I want is that a files content are read and transferred over the network to the server that writes it down to a different file .
What the code presently does is :
<<<<Client Code >>>>
It reads a file input.txt and sends the content over the network to the server.
<<<< Server Code >>>
It reads the incoming data from the client and writes the data out to a file called output.txt
What I want now is that the server should read the file output.txt and send the contents to the client which reads it and then writes it down as a new file called serverouput.txt . After that I want to compare and see of the size of input.txt and serveroutput.txt . If both are same that means that data has been written reliably to the server.
I have been trying to implement it for a long time and nothing seems to work out. I am posting the code for both client and server below. Any help in finalising things would be really appreciated.
CLIENT CODE
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import java.util.Date;
import java.io.*;
import java.net.*;
class sc {
static final int PORT = 4444; //Change this to the relevant port
static final String HOST = "127.0.0.1";
//Change this to the relevant HOST,
//(where Server.java is running)
public static void main(String args[]) {
try {
System.out.print("Sending data...\n");
Socket skt = new Socket(HOST, PORT);
// Set the socket option just in case server stalls
skt.setSoTimeout ( 2000 );
skt.setSoKeepAlive(true);
//Create a file input stream and a buffered input stream.
FileInputStream fis = new FileInputStream("input.txt");
BufferedInputStream in = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream( skt.getOutputStream() );
//Read, and write the file to the socket
int i;
while ((i = in.read()) != -1) {
out.write(i);
//System.out.println(i);
// Enable SO_KEEPALIVE
out.flush();
out.close();
in.close();
skt.close();
catch( Exception e ) {
System.out.print("Error! It didn't work! " + e + "\n");
catch( IOException e ) {
System.out.print("Error! It didn't work! " + e + "\n");
SERVER CODE
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import java.util.Date;
import java.io.*;
import java.net.*;
class ClientWorker implements Runnable {
private Socket client;
ClientWorker(Socket client) {
this.client = client;
public void run(){
try {
FileOutputStream fos = new FileOutputStream("output.txt");
BufferedOutputStream out = new BufferedOutputStream(fos);
BufferedInputStream in = new BufferedInputStream( client.getInputStream() );
//Read, and write the file to the socket
int i;
while ((i = in.read()) != -1) {
out.write(i);
//System.out.println(i);
System.out.println("Receiving data...");
out.flush();
in.close();
out.close();
client.close();
// srvr.close();
System.out.println("Transfer complete.");
catch(Exception e) {
System.out.print("Error! It didn't work! " + e + "\n");
class ss1 {
ServerSocket server = null;
ss1(){ //Begin Constructor
} //End Constructor
public void listenSocket(){
try{
server = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Could not listen on port 4444");
System.exit(-1);
while(true){
ClientWorker w;
try{
w = new ClientWorker(server.accept());
Thread t = new Thread(w);
t.start();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
protected void finalize(){
//Objects created in run method are finalized when
//program terminates and thread exits
try{
server.close();
} catch (IOException e) {
System.out.println("Could not close socket");
System.exit(-1);
public static void main(String[] args){
ss1 frame = new ss1();
frame.listenSocket();
}
............................................. After that I want to
compare and see of the size of input.txt and
serveroutput.txt . If both are same that means that
data has been written reliably to the server.You don't need to do this. TCP/IP ensures the reliable transmition of data. By using a socket you are automaticaly sure that the data is reliably transmitted (Unless there is some sort of exception).
To get the size of the files you can use a File object. Look it up in java.io package in API documentation.
java-code-snippet (without error checking)
File clientFile = new File("input.txt");
clientFile.length();
Similar Messages
-
Logic froze while I was working on something so I forced quit. Now every time I open LOGIC a message pops up that says:
"Error reading/writing file
“com.apple.logic.pro.cs”:
Logical end-of-file reached during read operation."
The only button option is cancel so I press it and another message appears that says:
"The Preferences are not loaded completely.
Do not save them, as you would overwrite the Preferences file with incomplete data."
Then when i close logic a box appears saying:
"The Preferences are not loaded completely.
Save them to "com.apple.logic.pro.cs" anyway?"
There are 3 button options to press; ok, cancel or dont save.
I press "don’t save" cuz I don't want to ruin anything.
I found a discussion located here: https://discussions.apple.com/message/9564253#9564253 that says if I delete the file "com.apple.logic.pro.cs" it will resolve the problem. If I do this will I loose or mess anything up at all, automation, saved channel strips customizations, saved effects, synth, or ultrabeat customizations etc? Or especially will I loose any work I've done? I have hundreds pieces of music files I've created. I'm scared to mess anything up with all the hours and months of work I've done. Is there anyway to fix this without loosing anything? I'm using Logic Pro 8.
Thank youYou can safely delete this file - its the preference file for control surface settings - you haven't said whether you're actually using a control surface or not, if so, you will have to set it up again. A new file will be created when you fire Logic up again, but of course it will contain default settings. If you have a complicated control surface setup, remember to keep a backup copy somewhere in case any future problems arise.
Other than that, you really have nothing to be scared about - hopefully your problem is as simple as that and there isn't an underlying problem (a corrupt hard drive, for example). You seem concerned about losing work, so I guess you want to think about backing that up on a regular basis too. If you're saving your projects to your system drive, do get an external one for this. And also check that you have plent of free space on your system drive - you need to keep about a quarter or third of it free for your OS and programs to run properly (some temporarily stored files can be quite large). -
Downloading a binary file using sockets without length known
Hi all,
I'm trying to download a binary(.exe) file using socket, where the length of the file is not known. Please take a look at the code I'm using:
var readBin = socketBin.read();
<-- Here comes the code that checks for http Content-length header field
; If content-length field is available, then I'll use it to download file, else proceed with following code -->
pBar.reset("Downloading plugin..",null);pBar.hit(readBin.length);
while (1)
binFil.write(readBin); //'binFil' is the file, into which downloaded file is written.
readBin = socketBin.read();
pBar.hit(readBin.length);
if( socketBin.eof || readBin.length<=0){
break;}
binFil.write(readBin);
binFil.close();
socketBin.close();
Problem is: I'm able to download file within 10 seconds when content-length is known. But when content-length is not known, its taking about 1 and half minute to download, also the progress bar gets struck for much of time.
FYI: socket is opened in binary mode, file is getting downloaded correctly(even though it takes abt a minute). BTW Im using CS5.5 extendscript
I'm not able to figure out where the bug is.Hi, Srikanth:
Sevaral points.
#1 When posting code, please use the web interface and the >> icon and choose Syntax Highlighting >> Java. Otherwise your code is just too hard to read and gets misformatted.
#2 Apropos of #1, your script as written does not work, because this line:
url=url.replace(/([a-z]*):\/\/([-\._a-z0-9A-Z]*)(:[0-9]*)?\/?(.*)/,"$ 1/$2/$3/$4");
has an extra space in the $1 and should be this:
url=url.replace(/([a-z]*):\/\/([-\._a-z0-9A-Z]*)(:[0-9]*)?\/?(.*)/,"$1/$2/$3/$4");
Please take an extra moment to make sure that when you asking for help, you do so in a way that makes sense. Otherwise it takes too much effort to help you, and that is frustrating.
#3 If we instrument your script by adding a line to the while() loop:
while (1)
binFil.write(readBin);
readBin = socketBin.read();
$.writeln(Date()+" Read "+readBin.length+" chars, eof is "+socketBin.eof);
if( readBin.length<=0){ break;}
We get output like this:
Mon Jul 11 2011 12:06:56 GMT-0400 Read 1024 chars, eof is false
Mon Jul 11 2011 12:06:56 GMT-0400 Read 1024 chars, eof is false
Mon Jul 11 2011 12:06:56 GMT-0400 Read 1024 chars, eof is false
Mon Jul 11 2011 12:06:56 GMT-0400 Read 631 chars, eof is false
Mon Jul 11 2011 12:07:06 GMT-0400 Read 0 chars, eof is false
Result: undefined
Therefore, we can reasonably conclude that the last read at the end of the data stream returns a short read when the other side blocks.
Unfortunately, that's clearly insufficient since you can get short reads all the time.
I'm not sure why you say the length of the file is not known, HTTP provides it to you in the Content-Length field of the response.
But the easy answer is to get the server to close it for you. This is easy, enough, with Connection: close. Why were you specifying
Connection: keep-alive, anyhow?:
var requestBin =
"GET /" + parsedURLBin.path + " HTTP/1.1\n" +
"Host: " + parsedURLBin.address + "\n" +
"User-Agent: InDesign ExtendScript\n" +
"Accept: */*\n" +
//"Connection: keep-alive\n\n";
"Connection: close\n"+
"\n";
This yields a nice tidy:
Mon Jul 11 2011 12:26:19 GMT-0400 Read 1024 chars, eof is false
Mon Jul 11 2011 12:26:19 GMT-0400 Read 1024 chars, eof is false
Mon Jul 11 2011 12:26:19 GMT-0400 Read 1024 chars, eof is false
Mon Jul 11 2011 12:26:19 GMT-0400 Read 735 chars, eof is true
Mon Jul 11 2011 12:26:19 GMT-0400 Read 0 chars, eof is true
I suspect you're also better off using something like socketBin.read(64*1024) for a 64k buffer size, but it doesn't seem to effect the on-the-wire protocol, so perhaps its not so important.
If you don't want to reply on the server -
Send a picture file using sockets
Hi,
Could someone please tell me how I can send a picture file using sockets across a TCP/IP network? I have managed to do it by converting the file into a byte array and then sending it but I dont see the data back at the client when I recieve the file. I just see the byte array as having size 0 at client.
Byte array size is correct at client side.
//client code
System.out.println("Authenticating client");
localServer = InetAddress.getLocalHost();
AuthConnection = new Socket(localServer,8189);
out = new PrintWriter(AuthConnection.getOutputStream());
InputStream is = AuthConnection.getInputStream();
System.out.println(is.available());
byte[] store = new byte[is.available()];
is.read(store);
ImageIcon image = new ImageIcon(store);
JLabel background = new JLabel(image);
background.setBounds(0, 0, image.getIconWidth(), image.getIconHeight());
getLayeredPane().add(background, new Integer(Integer.MIN_VALUE));
//extra code here
catch (UnknownHostException e) {
System.err.println("Don't know about host: LocalHost");
System.exit(1);
catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: LocalHost");
System.exit(1);
//server code
DataOutputStream out = new DataOutputStream(incoming.getOutputStream());
FileInputStream fin = new FileInputStream("3trees.gif");
byte[] b = new byte[fin.available()];
int ret = fin.read(b);
out.write(b);i used OutputStream as
OutputStream out = incoming.getOutputStream(); and flushed the stream too.
But I still get the same output on the client side. I tried sending a string and it works , but I cant seem to be able to populate the byte array on the client side. It keeps showing zero. Please advise.
Thank you. -
Performance issue: Tuning Reading/Writing to a Socket.
I have use case where reading/writing to a Socket is spending over 25% of the time in NativeThread.current() (Called from within SocketChannelImpl) This is a native call and it occurred to me that there might be a Java JNI option which could improve this call in particular.
This may be hprof giving incorrect information, but I don't know how to provide this. YourKit also shows this method as a big hit.
I am not so worried about read0 and write0 as this is directly related to what the use case does.
Can anyone suggest tuning options which might improve the performance of this call?
Does anyone know a way to determine if the information regarding this call is accurate?
TRACE 300250:
sun.nio.ch.FileDispatcher.read0(FileDispatcher.java:Unknown line)
sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:21)
sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:233)
sun.nio.ch.IOUtil.read(IOUtil.java:200)
sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:236)
my.AbstractSocket.readMessage(AbstractSocket.java:69)
TRACE 300225:
sun.nio.ch.FileDispatcher.write0(FileDispatcher.java:Unknown line)
sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:29)
sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:104)
sun.nio.ch.IOUtil.write(IOUtil.java:60)
sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:334)
my.AbstractSocket.flush(AbstractSocket.java:47)
my.AbstractSocket.sendMesg(AbstractSocket.java:37)
TRACE 300259:
sun.nio.ch.NativeThread.current(NativeThread.java:Unknown line)
sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:331)
my.AbstractSocket.flush(AbstractSocket.java:47)
my.AbstractSocket.sendMesg(AbstractSocket.java:37)
TRACE 300229:
java.nio.Bits.copyToByteArray(Bits.java:Unknown line)
java.nio.DirectByteBuffer.get(DirectByteBuffer.java:224)
my.FieldFormat.readString(BoltFieldFormat.java:56)
TRACE 300265:
sun.nio.ch.NativeThread.current(NativeThread.java:Unknown line)
sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:182)
my.AbstractSocket.readMessage(AbstractSocket.java:69)
CPU SAMPLES BEGIN (total = 11263) Tue Jul 14 16:29:15 2009
rank self accum count trace method
1 32.50% 32.50% 3660 300250 sun.nio.ch.FileDispatcher.read0
2 30.68% 63.18% 3456 300225 sun.nio.ch.FileDispatcher.write0
3 21.84% 85.02% 2460 300259 sun.nio.ch.NativeThread.current
4 6.82% 91.84% 768 300229 java.nio.Bits.copyToByteArray
5 5.69% 97.53% 641 300265 sun.nio.ch.NativeThread.currentI would ignore it. All it does is:
'Returns an opaque token representing the native thread underlying the invoking Java thread. On systems that do not require signalling, this method always returns -1.'I think the significant thing is that it is called while synchronized on 'stateLock', so if you have > 1 thread executing writes, the entire sync block will tend to be a bottleneck. I would aggregate the data for current() and read0(), or current() and write0(), and treat it all as I/O time. -
Oracle BAM to monitor transfer of files using sockets
Hi,
We have two programs transferring files using sockets. We wanted BAM to monitor the transfer.
Would you please suggest if this is achievable in BAM , and if so , any pointers to how we may go about implementing it .
Cheers,
Anant.You could generate success/failure/progress from your utility to JMS or call BAM webservices to populate BAM Data Objects. Reports could be built on top of that.
-
I wanted to know of a good way to move, not copy, files using sockets? Any help would be great.
ThanksEven on the same machine, you can only move a file on the same filesystem. i.e. the file appears in a different directory rather than copying the file.
If you have an C: and D: drive for example it will copy and delete the file on a move.
Unix allows you to have symbolic links which can make a file/directory from anywhere appear anywhere on your filesystem. It does not copy or actaully move the file, it just appears to be where ever you choose. -
Hey all! Don't know if anyone can help but I keep getting the message...
" Error reading/writing file "com.garageband.cs":`≤Ć». " with a cancel button.
If you click on it it does go away, but after a time playback starts skipping and stuff.
Anyone help please?
Thanks
Righinifirst two things to try for “oddball” probs:
http://www.bulletsandbones.com/GB/GBFAQ.html#oddballprobs
(Let the page FULLY load. The link to your answer is at the top of your screen) -
Error reading/writing file message when opening garageband and/or files
I've been recently getting this message when I open garageband and files
"Error reading/writing file\U201Ccom.apple.garageband.cs\U201D
I've been in and repaired disk permissions and all that it says it is all fine, reinstall garageband and message still comes up, weird.
not only is garageband being a nuisance, Mac OS X 10.6.2 is being a pain when shutting down telling me to restart the computer. This only happened since upgrading to 10.6. No one as yet knows this promble so I'm gonna have to ring apple and see what is going on here.
and also my other problem is that mac doesn't seem as snappy anymore I noticed this before upgrading to 10.6 and made no difference when "cleanly" installing 10.6. I get a colour wheel popping up and i'm having to wait with simple tasks. iMac only 2 years old.i give up with this discussion forum no no one knows anything
-
How to read pdf files using java.io package classes
Dear All,
I have a certain requirement that i should read and write PDF files at runtime. With normal java file IO reading is not working. Can any one suggest me how to proceed probably with sample code block
Thanks in advance.hi I also have the pbm. to read pdf file using JAVA
can any body help meWhy is it so difficult to read the thread you posted in? They say: java.io is pointless, use iText. So why don't you?
or also I want to read a binary encoded data into
ascii,
can anybody give me a hint how to do it.Depends on what you mean with "binary encoding". ASCII's binary encoding, too, basically. -
Reading XML file using BAPI and then uploading that xml file data into SAP
I am getting a xml file from Java server. I need to take
data from this file using BAPI and need to upload into SAP using SAP.
Please tell me how to read XML files using BAPI's.<b>SDIXML_DATA_TO_DOM</b> Convert SAP data (elementary/structured/table types) into DOM (XML
<b>SDIXML_DOM_TO_XML</b> Convert DOM (XML) into string of bytes that can be downloaded to PC or application server
<b>SDIXML_DOM_TO_SCREEN</b> Display DOM (XML)
<b>SDIXML_DOM_TO_DATA</b>
data: it_table like t001 occurs 0.
data: l_dom TYPE REF TO IF_IXML_ELEMENT,
m_document TYPE REF TO IF_IXML_DOCUMENT,
g_ixml TYPE REF TO IF_IXML,
w_string TYPE XSTRING,
w_size TYPE I,
w_result TYPE I,
w_line TYPE STRING,
it_xml TYPE DCXMLLINES,
s_xml like line of it_xml,
w_rc like sy-subrc.
start-of-selection.
select * from t001 into table it_table.
end-of-selection.
initialize iXML-Framework ****
write: / 'initialiazing iXML:'.
class cl_ixml definition load.
g_ixml = cl_ixml=>create( ).
check not g_ixml is initial.
write: 'ok'.
create DOM from SAP data ****
write: / 'creating iXML doc:'.
m_document = g_ixml->create_document( ).
check not m_document is initial.
write: 'ok'.
write: / 'converting DATA TO DOM 1:'.
CALL FUNCTION 'SDIXML_DATA_TO_DOM'
EXPORTING
NAME = 'IT_TABLE'
DATAOBJECT = it_table[]
IMPORTING
DATA_AS_DOM = l_dom
CHANGING
DOCUMENT = m_document
EXCEPTIONS
ILLEGAL_NAME = 1
OTHERS = 2.
if sy-subrc = 0. write 'ok'.
else. write: 'Err =', sy-subrc.
endif.
check not l_dom is initial.
write: / 'appending DOM to iXML doc:'.
w_rc = m_document->append_child( new_child = l_dom ).
if w_rc is initial. write 'ok'.
else. write: 'Err =', w_rc.
endif.
visualize iXML (DOM) ****
write: / 'displaying DOM:'.
CALL FUNCTION 'SDIXML_DOM_TO_SCREEN'
EXPORTING
DOCUMENT = m_document
EXCEPTIONS
NO_DOCUMENT = 1
OTHERS = 2.
if sy-subrc = 0. write 'ok'.
else. write: 'Err =', sy-subrc.
endif.
convert DOM to XML doc (table) ****
write: / 'converting DOM TO XML:'.
CALL FUNCTION 'SDIXML_DOM_TO_XML'
EXPORTING
DOCUMENT = m_document
PRETTY_PRINT = ' '
IMPORTING
XML_AS_STRING = w_string
SIZE = w_size
TABLES
XML_AS_TABLE = it_xml
EXCEPTIONS
NO_DOCUMENT = 1
OTHERS = 2.
if sy-subrc = 0. write 'ok'.
else. write: 'Err =', sy-subrc.
endif.
write: / 'XML as string of size:', w_size, / w_string.
describe table it_xml lines w_result.
write: / 'XML as table of', w_result, 'lines:'..
loop at it_xml into s_xml.
write s_xml.
endloop.
write: / 'end of processing'.
end of code
Hope this will be useful.
regards
vinod -
Reading XML file using BAPI I must use adapters .
Reading XML file using BAPI and then uploading that xml file data into SAP using BDC.
I cant take file on to my Application server I am getting the file dynamically from other file server and I need to use BAPis to read data from XML file.please tell me what should be my Import,Export and Tables parameterrs should be.
ThanksHi,
Import, export and table parameters for BAPI is required, without that BAPI will not able to collect the data from XML. What you need to do is write a Zprogram and collect the data, store that data in internal table and call the BAPI by passing required parameters.
Different Scanarios:
1) Before calling a BAPI write some other program which collects the data from XML and create a UNIX file. Try to get the data from UNIX FILE
2) If you see the XML tags, data will be in side that tags, try to get the data from XML tags and store that data in one SAP table. You can use the BAPI by fetching the data from table
3)Create a table and store the data in the table. Use the table in SAP to extract the data.
BAPI won't work without any parameters, you have to pass some parameters then the BAPI will return some values.
Hope i am clear.
Thanks&Regards,
-Suresh Revuru -
How to read HTML files using UTL_FILE
Hello Friends,
How to read HTML files using UTL_FILE package ? According
to Oracle documentation UTL_FILE can read or write OS Text Files.
Thanx in advance..
AdiHI Hareesh,
i have gone through that blog.
i tried it...but i am getting mapping error no receiver determination fond because there are so many excel files.
my data is available on sharedString.xml but also it is in not same order.
i have no clue how to handle this part form the blog.
"This way our mapping will receive all data from the sheet in an XML format. The only thing that's left is to create an XSD file from the XML file we received in order to be able to use it in the mapping and as our Service Interface and we can proceed with mapping. As you can see from the sheet.xml files all the data is placed with column name and row number so it's not that difficult to map it to an table type format using the Message Mapping only (no java, abap mapping required)." -
Is it possible to read the file using File Adapter which is in client machi
Is it possible to read the file using file Adapter which is in client machine(on the same network).Then what is thee need of FTP Adapter?
You can achieve that by exposing your client machine as a drive, then you can go using file adapter.
FTP adapter will help you to communicate with different machine which is in different network.
It is considered good etiquette to reward answerers with points (as "helpful" - 5 pts - or "correct" - 10pts).
Thanks,
Vijay -
How to read pdf file using file adapter
Hi..
How to read pdf file using file adapter?
regards
ArunHi
This may help you
/people/sap.user72/blog/2005/07/27/xi-generate-pdf-file-out-of-file-adapter
/people/alessandro.guarneri/blog/2007/02/21/sap-xi-acting-as-a-huge-file-mover
---Ram
Maybe you are looking for
-
Ok, having an issue with security and will give an overview of security setup and the issue. First, security structure. We are using a Web SSO, so users go to this SSL website, enter their LAN ID and password to login which redirects to Answers. The
-
Hi, I'm wondering if you can add alerts to a web page like this one? http://www.ashburnvillage.org/link/linkshow.asp?link_id=358147 We'd like to be able to post school closings and that kind of thing. Ideally we'd like to pull data from like a local
-
IPhone 32 GB 3GS TV output with Monster iTV Link
I have used my Monster iTV Link cable http://www.monstercable.com/productdisplay.asp?pin=3897 to connect my 80GB 5th generation ipod (through the dock port on the bottom) to my Chevy Avalance's AUX Video input via left, right audio and video plug. Wh
-
Hi everyone, I'm new to Flex, and I see that creating a pie chart is normally very easy with the Pie Chart component. However, I need to create a pie chart where the edges of the slices are draggable. In other words, I want the user to be able to res
-
Holder of two positions, reporting to multiple managers in Travel managemen
Dear Consultants, Our configuration is as follows: We have implemented Travel Management in our organization. A Person is assigned %70 capacity of Position A, and is assigned %30 capacity of Position B. Position A is reporting to Position X and Pos