Writing to a port(Socket)
I have an input file that I need to first write to a port and read this data from the port.
Briefly,
I have to write one line to the port and then read it from there and process.
Next read the 2nd line and read it from port and process..
and so on till the end of the file.....
I'm new to socket programming and just started it. PLease help.
Thanks !
RC
[403 byte] By [
cratnama] at [2007-11-27 11:45:04]

# 1
something like this may be what you want..
//some variables to use..
private static final LOCAL_HOST = "127.0.0.1";
private static final A_PORT = "12345";
class ReaderSocket
{
public ReaderSocket()
{
Socket reader = new Socket( LOCAL_HOST, A_PORT );
Socket writer = reader.accept();
// Get the input stream of the writer Socket so we can see what is being sent to us.
BufferedReader in = new BufferedReader( new InutStreamReader( writer.getInputStream());
String dataWritten;
while( ( dataWritten = in.readLine() ) != null )
processData( dataWritten ); // do your processing..
in.close();
}
}
class WriterSocket
{
public WriterSocket( String fileToWrite )
{
Socket writer = new Socket( LOCAL_HOST, A_PORT );
BufferedWriter out = new BufferedWriter( new OutputStreamWriter( writer.getOutputStream() ) );
Scanner scnr = null;
try
{
scnr = new Scanner( new File( fileToWrite ) );
whle( scnr.hasNextLine() )
out.write( scnr.nextLine() );
}
catch( FileNotFoundException e )
{
System.out.println( "Cannot find the specified file to write to ReaderSocket.");
}
finally
{
if( scnr != null )
scnr.close();
out.close();
}
}
}
Now in order to implement these two classes, you might do this...
public static void main( String[] args )
{
new ReaderSocket( );
new WriterSocket( "mytextfile.txt" );
}
Hope this helps.. if you have any problems or errors lemme know. I wrote this off the top of my head, so there could be minor errors, however the jist of it is correct.