Client named pipe in Powershell not connecting to server in Java - java

I implemented a simple bi-directional pipe server in Java using JNA, respectively a client in Powershell.
Basically, I expect the client to connect, send a message to the server and finally get a message back from the server.
The actual results are different though. When I run the server first and then the client, the client waits forever to connect, while the server connects and then waits to read the message from the pipe.
The code in Java for the server, respectively the code in Powershell for the client can be seen below.
Any idea how to solve this issue?
Thanks!
static final int MAX_BUFFER_SIZE = 1024;
static String pipeName = "\\\\.\\pipe\\testpipe";
static HANDLE namedPipe;
public static void main(final String[] args) {
createPipe();
runServerFile();
}
private static void createPipe() {
namedPipe = INSTANCE.CreateNamedPipe(pipeName,
WinBase.PIPE_ACCESS_DUPLEX , // dwOpenMode
WinBase.PIPE_TYPE_BYTE | WinBase.PIPE_READMODE_BYTE | WinBase.PIPE_WAIT,// | WinBase.PIPE_READMODE_MESSAGE | WinBase.PIPE_TYPE_MESSAGE, // dwPipeMode
WinBase.PIPE_UNLIMITED_INSTANCES , // nMaxInstances,
//WinBase.PIPE_UNLIMITED_INSTANCES, // nMaxInstances (255),
Byte.MAX_VALUE, // nOutBufferSize,
Byte.MAX_VALUE, // nInBufferSize,
1000, // nDefaultTimeOut,
null); // lpSecurityAttributes
System.out.println("Created pipe: " + namedPipe.toString() + " invalid_handle = " + WinBase.INVALID_HANDLE_VALUE.toString());
System.out.println("Last error: " + Native.getLastError());
}
private static void runServerFile() {
RandomAccessFile npipeClient = null;
try {
System.out.println("br1");
npipeClient = new RandomAccessFile(pipeName, "rws");
INSTANCE.ConnectNamedPipe(namedPipe,null);
byte[] buffer = new byte[100];
int rd_count;
String recv;
System.out.println("Connected pipe");
do{
System.out.println("Before read");
rd_count = npipeClient.read(buffer);
if(rd_count<0) break;
System.out.println("After read");
recv = new String(buffer,0, rd_count);
System.out.println("Received" + recv);
}while(!recv.equalsIgnoreCase("done"));
System.out.println("Received correct message");
//npipeClient.write("Hello world!".getBytes());
npipeClient.writeUTF("Hello back!");
//npipeClient.getFD().sync();
//INSTANCE.FlushFileBuffers(new HANDLE(npipeClient.getFD().));
System.out.println("Sent: Hello back");
npipeClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
param ($ComputerName = '.')
$npipeClient = new-object System.IO.Pipes.NamedPipeClientStream($ComputerName, 'testpipe', [System.IO.Pipes.PipeDirection]::InOut,
[System.IO.Pipes.PipeOptions]::None,
[System.Security.Principal.TokenImpersonationLevel]::Impersonation)
$pipeReader = $pipeWriter = $null
function WriteToPipeAndLog($msg) {
$msg
$pipeWriter.WriteLine($msg)
}
try {
'Client connecting to sever'
$npipeClient.Connect()
'Connected to server'
$pipeReader = new-object System.IO.StreamReader($npipeClient)
$pipeWriter = new-object System.IO.StreamWriter($npipeClient)
$pipeWriter.AutoFlush = $true
Write-Host "Sent: Hello world!"
$pipeWriter.WriteLine('Hello world!')
$pipeWriter.WriteLine('How ya doing')
$pipeWriter.WriteLine('Done')
while (($line = $read.ReadLine()) -ne $null)
{
Write-Host "Received: " $line
}
}
finally {
'Client exiting'
$npipeClient.Dispose()
}

Related

Java socket connection with Qt

I'm trying to connect a very simple java socket client to a QTcpServer. However, while it connects, I can't send messages to and from. I have also tried connecting the java client to a java server (works nicely) and the Qt server to a qt client (also works nicely). But mixing them somehow doesn't..
Here's the Java client:
public class SocketClient {
public static void main(String[] args) throws IOException {
String hostName = "10.57.140.129";
int portNumber = 2010;
try (
Socket kkSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(kkSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(kkSocket.getInputStream()));
) {
BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Test recieved. KKTHXBYE"))
break;
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
With the bits of the QTserver code that is relevant:
#include "socketserver.h"
SocketServer::SocketServer(QObject *parent) :
QTcpServer(parent) {
}
void SocketServer::StartServer(){
if(!this->listen(QHostAddress::Any, 2010)){
qDebug() << "Could not start server";
}else{
qDebug() << "Listening...";
}
}
void SocketServer::incomingConnection(qintptr socketDescriptor){
qDebug() << socketDescriptor << " Connecting...";
SocketThread *thread = new SocketThread(socketDescriptor,this);
connect(thread, SIGNAL(finished()),thread, SLOT(deleteLater()));
connect(thread, SIGNAL(newData(QByteArray)), this, SLOT(incomeData(QByteArray)));
thread->start();
}
void SocketServer::incomeData(QByteArray newData){
emit sendBack(newData);
}
Thread:
#include "socketthread.h"
SocketThread::SocketThread(qintptr ID, QObject *parent) :
QThread(parent) {
this->socketDescriptor = ID;
}
void SocketThread::run(){
//thread starts here
qDebug() << socketDescriptor << " Starting thread";
socket = new QTcpSocket();
if(!socket->setSocketDescriptor(this->socketDescriptor)){
emit error(socket->error());
return;
}
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()), Qt::DirectConnection);
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()), Qt::DirectConnection);
qDebug() << socketDescriptor << " Client Connected";
writeBack("connected");
exec();
}
void SocketThread::readyRead(){
QByteArray incomeData = socket->readAll();
qDebug() << socketDescriptor << " Data in: " << incomeData;
emit newData(incomeData);
}
void SocketThread::writeBack(QByteArray Data){
socket->write(Data);
}
void SocketThread::disconnected(){
qDebug() << socketDescriptor << " Disconnected";
socket->deleteLater();
exit(0);
}
Like mentioned, the client connects, and these debug outputs are written:
924 Connecting...
924 Starting thread
924 Client Connected
But no matter what I try to write from the client, it never picks up on anything with the readyReady() function. Any ideas? Am I missing specific endings on the lines I'm writing? (I've tried \r\n and \0, they don't seem to do much)
It seems like you are using line-based processing in Java but not in C++:
in.readLine() vs. socket->readAll()
and
out.println(fromUser) vs. writeBack("connected");
The C++ just never sends a CR/LF, which is not a problem when the other end does not expect one -> readAll(). The Java side however does expect (and send) CR/LF because you use BufferedReader.readLine() and BufferedWriter.writeln().
Decide if you want line-based communication or not and then adapt the C++ or the Java side accordingly.

Multi threaded TCP server in Java does not reply TCP Client in C

I'm trying to test a Multi threaded TCP MuxServer in Java with a TCP client coded in C. below the code of the part which manages the communication with the client:
class Echo_TCP_Thread extends Thread
{
Socket Sock_Thr;
public Echo_TCP_Thread (Socket The_Socket)
{
this.Sock_Thr = The_Socket;
}
public void run()
{
try
{
PrintWriter output = new PrintWriter(Sock_Thr.getOutputStream());
InputStreamReader input = new InputStreamReader(Sock_Thr.getInputStream());
BufferedReader binput = new BufferedReader(input);
//
System.out.println ("Test 1"); //This message is displayed
//
String temp;
while ((temp=binput.readLine()) != null)
{
//
System.out.println ("Test 2"); //This message is not displayed
//
output.print(this.getName() + " answer -> ");
output.println(temp);
output.flush();
System.out.println ("Child Server : " + Thread.currentThread()
+ " has received" + temp);
}
}
catch (Exception e)
{
return;
}
finally
{
try
{
Sock_Thr.close();
System.out.println
("Child Server " + Thread.currentThread() + " : End !!! ");
}
catch (IOException e)
{
}
}
}
}
Even if I get connectivity and the end message is displayed in the client when I finish the communication, the client doesn't receive the echo messages from the server. I have checked with the Test messages that the program is not going into the while ((temp=binput.readLine()) != null) loop, but the message Test 1 is displayed right after I get connected to the server. What should I code to correct this?

Send a string command to a socket

I am not very familiar with telnet so I would appreciate the help from any willing.
I have smart plugs which can be switch on or off through a telnet interface.
I always use telnet via command prompt to connect to the server Digi X4 connect port (via >telnet ). If I want to switch the socket on/off, I have to now type: "12 set pow=on/off" and press enter.
I would like to implement this through java using the telnet client. I am now able to connect to the port (thanks to the answers posted on this platform), but to send the command to switch devices on/off is proving difficult for me. I still have to type "12 set pow=on/off" and press enter. I would like Java to send this command.
Below is my java code. I would appreciate your assistance. Bab
public class TelnetConnection {
static TelnetClient tc = null;
public static void main(String[] a) throws Exception
{
String[] args = {"122.1222.181.45","8085"};
System.out.println("arg value: "+args);
if(args.length < 1)
{
System.err.println("Usage: Error <remote-ip> [<remote-port>]");
System.exit(1);
}
String remoteip = args[0];
int remoteport;
if (args.length > 1)
{
remoteport = (new Integer(args[1])).intValue();
}
else
{
remoteport = 7000;
}
tc = new TelnetClient();
while (true)
{
boolean end_loop = false;
try
{
tc.connect(remoteip, remoteport);
Thread reader = new Thread (new TelnetClientExample());
tc.registerNotifHandler(new TelnetClientExample());
System.out.println("TelnetClientExample");
reader.start();
OutputStream outstr = tc.getOutputStream();
PrintWriter out = new PrintWriter(outstr);
String buff = "11 set pow=on";
//int ret_read = 0;
do
{
try
{
out.print(buff);
outstr.flush();
}
catch (IOException e)
{
System.err.println("Error");
end_loop = true;
}
}
while((true) && (end_loop == false));
try
{
tc.disconnect();
}
catch (IOException e)
{
System.err.println("Error");
}
}
catch (IOException e)
{
System.err.println("Exception while connecting:" + e.getMessage());
System.exit(1);
}
}
}
}
Try tring buff = "11 set pow=on\n"; the server may need the newline to detect end-of-command.
By the way, the loop that infinitely sends that to the server looks worrisome.
You need to send a line terminator corresponding to 'and press Enter'.
The line terminator in Telnet is defined as \r\n.

Java Telegram API RpcCall Timeout

I have a Problem regarding the Telegram API
Whenever I do a RpcCall, it always give me a TimeoutException except when I do a NonAuth Call.
I can SignIn with a Number already and I set Authenticated to true in my AbsApiState and still can only do NonAuth Calls
Here is my Code:
private void startApi() throws Exception
{
api = new TelegramApi(new MyApiStorage(Moin.config.getProp("useTest").equalsIgnoreCase("true") ? true : false),
new AppInfo(Moin.api_id, "console", "???", "???", "en"),
new ApiCallback()
{
#Override
public void onAuthCancelled(TelegramApi arg0)
{
System.out.println("AuthCancelled");
}
#Override
public void onUpdate(TLAbsUpdates update)
{
System.out.println("Updated | " + update.getClass());
}
#Override
public void onUpdatesInvalidated(TelegramApi arg0)
{
System.out.println("Updatefailed");
}
});
TLConfig config = null;
config = api.doRpcCallNonAuth(new TLRequestHelpGetConfig());
if(config != null)
api.getState().updateSettings(config);
else
throw new Exception("config is null, could not update DC List");
login();
}
private void login() throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
TLSentCode code = null;
String defaultNumber = Moin.config.getProp("phoneNumber");
System.out.println("Enter a Phone Number (Default ist " + defaultNumber + "):");
String number = reader.readLine();
if(number.equals(" "))
number = defaultNumber;
System.out.println("Sending to " + number + " ...");
try
{
code = api.doRpcCallNonAuth(new TLRequestAuthSendCode(number, 0, Moin.api_id, Moin.api_hash, "en"));
}
catch (RpcException e)
{
if (e.getErrorCode() == 303)
{
int destDC = 0;
if (e.getErrorTag().startsWith("NETWORK_MIGRATE_"))
{
destDC = Integer.parseInt(e.getErrorTag().substring("NETWORK_MIGRATE_".length()));
}
else if (e.getErrorTag().startsWith("PHONE_MIGRATE_"))
{
destDC = Integer.parseInt(e.getErrorTag().substring("PHONE_MIGRATE_".length()));
}
else if (e.getErrorTag().startsWith("USER_MIGRATE_"))
{
destDC = Integer.parseInt(e.getErrorTag().substring("USER_MIGRATE_".length()));
}
else
{
e.printStackTrace();
}
api.switchToDc(destDC);
code = api.doRpcCallNonAuth(new TLRequestAuthSendCode(number, 0, Moin.api_id, Moin.api_hash, "en"));
}
else
e.printStackTrace();
}
String hash = code.getPhoneCodeHash();
System.out.println("Please Enter the Code:");
String smsCode = reader.readLine();
TLAuthorization auth = api.doRpcCallNonAuth(new TLRequestAuthSignIn(number, hash, smsCode));
api.getState().setAuthenticated(api.getState().getPrimaryDc(), true);
//This is where I get the Error
TLExportedAuthorization test = api.doRpcCall(new TLRequestAuthExportAuthorization(api.getState().getPrimaryDc()));
System.out.println(test.getId());
FileOutputStream stream = new FileOutputStream(Paths.get("").toAbsolutePath().toString() + File.separator + "test.txt");
try
{
stream.write(test.getBytes().getData());
}
finally
{
stream.close();
}
TLState state = api.doRpcCall(new TLRequestUpdatesGetState());
System.out.println(state.getDate() + " | " + state.getPts() + " | " + state.getQts() + " | " + state.getUnreadCount());
TLAbsUser user = auth.getUser();
}
And here the Error:
TelegramApi#1001:Timeout Iteration
TelegramApi#1001:RPC #3: Timeout (14999 ms)
TelegramApi#1001:Timeout Iteration
org.telegram.api.engine.TimeoutException
at org.telegram.api.engine.TelegramApi.doRpcCall(TelegramApi.java:364)
at org.telegram.api.engine.TelegramApi.doRpcCall(TelegramApi.java:309)
at org.telegram.api.engine.TelegramApi.doRpcCall(TelegramApi.java:400)
at org.telegram.api.engine.TelegramApi.doRpcCall(TelegramApi.java:396)
at at.nonon.telegram.telegram.Telegram.login(Telegram.java:165)
at at.nonon.telegram.telegram.Telegram.startApi(Telegram.java:105)
at at.nonon.telegram.telegram.Telegram.<init>(Telegram.java:54)
at at.nonon.telegram.telegram.ApiManager.startNew(ApiManager.java:21)
at at.nonon.telegram.Moin.onApiStart(Moin.java:31)
I took alot of the Code from the telegram-bot (https://github.com/ex3ndr/telegram-bot) but even if I copy paste his Code, it still doesn't work...
Thanks in Advance
this problem happened to me, too. I assume you are on a debian or some other linux box. The problem is Oracle JDK's use of the linux random number generator.
In order to make it work, run your application like this:
java -Djava.security.egd=file:/dev/./urandom -jar foo.jar
... meaning, you have to specify the java.security.egd parameter.
Details can be found here: https://github.com/ex3ndr/telegram-api/issues/9#issuecomment-38175765
and here:
http://www.virtualzone.de/2011/10/javas-securerandomgenerateseed-on-linux.html
It started working for me after I changed the server IP address in MemoryApiState as shown below
public void start(boolean isTest) {
connections = new HashMap<>();
connections.put(1, new ConnectionInfo[]{
new ConnectionInfo(1, 0, isTest ? "149.154.175.10" : "149.154.175.50", 443),
});
}
Your timeout might happen for several reasons - please see my answer to TimeoutException on telegram java client

java.lang.Exception: Error while transmitting data how to solve this error

I am trying to send a file from server side to client side upon request. The file that is sent is encrypted and the client shpuld decrypt it. the encryption process works fine but while decrypting i need to have the DerIOBuffer objetc which I have using serializing. what should i do..please help
server:
import java.net.*;
import java.io.*;
import java.math.BigInteger;
import com.dragongate_technologies.borZoi.*;
public class FileServer {
static final int LISTENING_PORT = 3210;
public static void main(String[] args) {
File directory; // The directory from which the gets the files that it serves.
ServerSocket listener; // Listens for connection requests.
Socket connection; // A socket for communicating with a client.
/* Check that there is a command-line argument.
If not, print a usage message and end. */
if (args.length == 0) {
System.out.println("Usage: java FileServer <directory>");
return;
}
/* Get the directory name from the command line, and make
it into a file object. Check that the file exists and
is in fact a directory. */
directory = new File(args[0]);
if ( ! directory.exists() ) {
System.out.println("Specified directory does not exist.");
return;
}
if (! directory.isDirectory() ) {
System.out.println("The specified file is not a directory.");
return;
}
/* Listen for connection requests from clients. For
each connection, create a separate Thread of type
ConnectionHandler to process it. The ConnectionHandler
class is defined below. The server runs until the
program is terminated, for example by a CONTROL-C. */
try {
listener = new ServerSocket(LISTENING_PORT);
System.out.println("Listening on port " + LISTENING_PORT);
while (true) {
connection = listener.accept();
new ConnectionHandler(directory,connection);
}
}
catch (Exception e) {
System.out.println("Server shut down unexpectedly.");
System.out.println("Error: " + e);
return;
}
} // end main()
static class ConnectionHandler extends Thread {
// An object of this class is a thread that will
// process the connection with one client. The
// thread starts itself in the constructor.
File directory; // The directory from which files are served
Socket connection; // A connection to the client.
TextReader incoming; // For reading data from the client.
PrintWriter outgoing; // For transmitting data to the client.
ConnectionHandler(File dir, Socket conn) {
// Constructor. Record the connection and
// the directory and start the thread running.
directory = dir;
connection = conn;
start();
}
void sendIndex() throws Exception {
// This is called by the run() method in response
// to an "index" command. Send the list of files
// in the directory.
String[] fileList = directory.list();
for (int i = 0; i < fileList.length; i++)
outgoing.println(fileList[i]);
outgoing.flush();
outgoing.close();
if (outgoing.checkError())
throw new Exception("Error while transmitting data.");
}
void ecies_ex(String fileName) throws Exception {
// This function encrypts the file that has been requested
// by the client.
String at1,dc1,der1;
OutputStream os = connection.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
ECDomainParameters dp = ECDomainParameters.NIST_B_163();
ECPrivKey skA = new ECPrivKey(dp, BigInteger.valueOf(123));
ECPubKey pkA = new ECPubKey(skA);
ECPrivKey skB = new ECPrivKey(dp, BigInteger.valueOf(230));
ECPubKey pkB = new ECPubKey(skB);
File file = new File(directory,fileName);
if ( (! file.exists()) || file.isDirectory()) {
// (Note: Don't try to send a directory, which
// shouldn't be there anyway.)
outgoing.println("error");
}
else {
outgoing.println("ok");
String pt1 = new String();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(fileName));
while ((sCurrentLine = br.readLine()) != null) {
pt1=pt1+"\n"+sCurrentLine;
}
} catch (IOException e) {
e.printStackTrace();
}
ECIES crypt = new ECIES(skA, pkB, pt1.getBytes()); // encrypt the data
try {
DerIOBuffer der = new DerIOBuffer(crypt);
oos.writeObject(der);
ECIES decrypt = der.toECIES();
dc1=decrypt.toString2(); //cipher text
//at1=decrypt.toString3(); //authentication tag
FileWriter fstream = new FileWriter("encrypted.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(dc1);
//Close the output stream
out.close();
} catch (Exception e) {
System.out.println(e.toString());
}
TextReader fileIn = new TextReader( new FileReader("encrypted.txt") );
while (fileIn.peek() != '\0') {
// Read and send lines from the file until
// an end-of-file is encountered.
String line = fileIn.getln();
outgoing.println(line);
}
}
outgoing.flush();
// oos.close();
// os.close();
outgoing.close();
if (outgoing.checkError())
throw new Exception("Error while transmitting data.");
}
public void run() {
// This is the method that is executed by the thread.
// It creates streams for communicating with the client,
// reads a command from the client, and carries out that
// command. The connection is logged to standard output.
// An output beginning with ERROR indicates that a network
// error occurred. A line beginning with OK means that
// there was no network error, but does not imply that the
// command from the client was a legal command.
String command = "Command not read";
try {
incoming = new TextReader( connection.getInputStream() );
outgoing = new PrintWriter( connection.getOutputStream() );
command = incoming.getln();
if (command.equals("index")) {
sendIndex();
}
else if (command.startsWith("get")){
String fileName = command.substring(3).trim();
ecies_ex(fileName);
//sendFile(fileName);
}
else {
outgoing.println("unknown command");
outgoing.flush();
}
System.out.println("OK " + connection.getInetAddress()
+ " " + command);
}
catch (Exception e) {
System.out.println("ERROR " + connection.getInetAddress()
+ " " + command + " " + e);
}
finally {
try {
connection.close();
}
catch (IOException e) {
}
}
}
} // end nested class ConnectionHandler
} //end class FileServer
client :
import java.net.*;
import java.io.*;
import java.math.BigInteger;
import com.dragongate_technologies.borZoi.*;
public class FileClient {
static final int LISTENING_PORT = 3210;
public static void main(String[] args) {
String computer; // Name or IP address of server.
Socket connection; // A socket for communicating with that computer.
PrintWriter outgoing; // Stream for sending a command to the server.
TextReader incoming; // Stream for reading data from the connection.
String command; // Command to send to the server.
String pt3;
ECDomainParameters dp = ECDomainParameters.NIST_B_163();
ECPrivKey skB = new ECPrivKey(dp, BigInteger.valueOf(230));
//ECPrivKey skB = new ECPrivKey (dp);
ECPubKey pkB = new ECPubKey(skB);
/* Check that the number of command-line arguments is legal.
If not, print a usage message and end. */
if (args.length == 0 || args.length > 3) {
System.out.println("Usage: java FileClient <server>");
System.out.println(" or java FileClient <server> <file>");
System.out.println(" or java FileClient <server> <file> <local-file>");
return;
}
/* Get the server name and the message to send to the server. */
computer = args[0];
if (args.length == 1)
command = "index";
else
command = "get " + args[1];
/* Make the connection and open streams for communication.
Send the command to the server. If something fails
during this process, print an error message and end. */
try {
connection = new Socket( computer, LISTENING_PORT );
incoming = new TextReader( connection.getInputStream() );
outgoing = new PrintWriter( connection.getOutputStream() );
outgoing.println(command);
outgoing.flush();
}
catch (Exception e) {
System.out.println(
"Can't make connection to server at \"" + args[0] + "\".");
System.out.println("Error: " + e);
return;
}
/* Read and process the server's response to the command. */
try {
if (args.length == 1) {
// The command was "index". Read and display lines
// from the server until the end-of-stream is reached.
System.out.println("File list from server:");
while (incoming.eof() == false) {
String line = incoming.getln();
System.out.println(" " + line);
}
}
else {
// The command was "get <file-name>". Read the server's
// response message. If the message is "ok", get the file.
String message = incoming.getln();
if (! message.equals("ok")) {
System.out.println("File not found on server.");
return;
}
PrintWriter fileOut; // For writing the received data to a file.
if (args.length == 3) {
// Use the third parameter as a file name.
fileOut = new PrintWriter( new FileWriter(args[2]) );
}
else {
// Use the second parameter as a file name,
// but don't replace an existing file.
File file = new File(args[1]);
if (file.exists()) {
System.out.println("A file with that name already exists.");
System.out.println("To replace it, use the three-argument");
System.out.println("version of the command.");
return;
}
fileOut = new PrintWriter( new FileWriter(args[1]) );
}
while (incoming.peek() != '\0') {
// Copy lines from incoming to the file until
// the end of the incoming stream is encountered.
String line = incoming.getln();
fileOut.println(line);
}
InputStream is = connection.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
DerIOBuffer der = (DerIOBuffer)ois.readObject();
ECIES decrypt = der.toECIES();
byte[] pt2 = decrypt.decrypt(skB); // decrypt the data
pt3=new String(pt2);
if (fileOut.checkError()) {
System.out.println("Some error occurred while writing the file.");
System.out.println("Output file might be empty or incomplete.");
}
}
}
catch (Exception e) {
System.out.println("Sorry, an error occurred while reading data from the server.");
System.out.println("Error: " + e);
}
} // end main()
} //end class FileClient
If you care about errors, you should not use PrintWriter. Why? Because if an error does occur on output via a PrintWriter, you have no way to find out what it was. This is what makes it difficult to figure out what the real problem is in this case. I recommend that you fix this so that you can get to the real cause of the problem.
The real problem could be related to to the following issues:
If the stuff you are trying to write could be binary, you shouldn't use PrintWriter ... or Readers / Writers at all.
You seem to be using Object serialization unnecessarily ... and on a class that looks like it may not be serializable.
Based on the difficulty I had in finding documentation for the "borZoi" library ... and other things ... I think you may have made a poor choice of library for doing crypto work.

Categories