I am trying to send a text file from the sender to the receiver however on the sender side I get connection refused: connect. I use a localhost address on the receiver side and I manually enter it in when prompt on the sender side. The error occurs at sendChannel.connect(address) in the sender class.
Sender class:
public static void startProcess(){
SocketChannel sendChannel = null;
RandomAccessFile f = null;
Scanner scan = new Scanner(System.in);
SocketAddress address = null;
try{
sendChannel = SocketChannel.open(); // open the channel
//DatagramSocket socket = dChannel.socket();
boolean validAddr = false;
while(validAddr != true){
try{
System.out.println("Enter in valid server IP Address");
address = new InetSocketAddress(scan.nextLine(),7777);
validAddr = true;
}
catch(Exception e){
System.out.println("Invalid!");
System.out.println(e.getMessage());
}
}
//System.out.println("Address: " + InetAddress.getLocalHost().getHostAddress());
sendChannel.connect(address);
File i = new File("./data.txt");
f = new RandomAccessFile(i,"r");
FileChannel fChannel = f.getChannel();
ByteBuffer bBuffer = ByteBuffer.allocate(1024); //set buffer capacity to 1024 bytes
while (fChannel.read(bBuffer) > 0) {
//SocketAddress client = dChannel.receive(bBuffer); //receive the datagram
bBuffer.flip(); //Set limit to current position
sendChannel.write(bBuffer);
//dChannel.send(bBuffer, client); //send the datagram using channel
bBuffer.clear(); //Get ready for new sequence of operations
}
Thread.sleep(1000);
System.out.println("End of file reached");
sendChannel.close();
f.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
Receiver side:
public static void startProcess(){
Scanner scan = new Scanner(System.in);
ServerSocketChannel serverChannel = null;
SocketChannel chan = null;
RandomAccessFile file = null;
try{
serverChannel = ServerSocketChannel.open();
//Read in a valid IP Address
boolean val2 = false;
int tempNum = 0;
for (int portNUM = 7777 ;!val2; portNUM++){
try {
serverChannel.socket().bind(new InetSocketAddress("localhost", portNUM));
tempNum = portNUM;
val2 =true;
} catch (IOException e) {
System.out.println("Error!");
}
}
System.out.println(InetAddress.getLocalHost().getHostAddress());
System.out.println("Port Number: " + tempNum);
chan = serverChannel.accept();
System.out.println("Connected!");
chan.getRemoteAddress();
file = new RandomAccessFile("./output.txt","rw");
ByteBuffer buff = ByteBuffer.allocate(1024);
FileChannel receiveChannel = file.getChannel();
while(chan.read(buff) > 0){
buff.flip();
receiveChannel.write(buff);
buff.clear();
}
// buff.put((byte)65 );
//buff.flip();
Thread.sleep(1000);
receiveChannel.close();
System.out.println("End of file");
chan.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
I figured it out I was using the localhost incorrectly on the Receiver side. I changed it to serverChannel.socket().bind(new InetSocketAddress(portNUM));
Related
I am trying to send an object from my server and then receiving it/displaying it on the client side. The object in question has a few parameters tied to it, such as int values and string values. Do I also need to have a version of my server class on the client side in which to store the values from the input stream?
I have tried the following:
Server
public void run() {
int height = 6;
int width = 9;
int moves = height * width;
System.out.println("Connected: " + socket);
try {
Server server = new Server(val1, val2, str1, str2);
Scanner scanner = new Scanner(socket.getInputStream());
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
ObjectOutputStream serverOutputStream = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream serverInputStream = new ObjectInputStream(socket.getInputStream());
// while (scanner.hasNextInt()) {
// printWriter.println(scanner.nextInt());
// }
System.out.println(server );
// printWriter.println(server );
serverOutputStream.writeObject(server );
// while (scanner.hasNextInt()) {
for (int player = 0; moves-- > 0; player = 1 - player) {
char symbol = PLAYERS[player];
server.doSomething(symbol, scanner);
// printWriter.println(scanner.nextInt());
System.out.println(server);
// printWriter.println(server);
serverOutputStream.writeObject(server);
if (server.hasWon()) {
System.out.println("\nPlayer " + symbol + " wins!");
return;
}
// }
}
} catch (Exception exception) {
System.out.println("Error: " + socket);
} finally {
try {
socket.close();
} catch (IOException e) {
}
System.out.println("Closed: " + socket);
}
}
Client
public static void main(String[] args) throws Exception {
// if (args.length != 1) {
// System.err.println("Pass the server IP as the sole command line argument");
//
// return;
// }
try (Socket socket = new Socket("127.0.0.1", 59898)) {
System.out.println("Enter a move: ");
Scanner scanner = new Scanner(System.in);
Scanner in = new Scanner(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
ObjectInputStream serverInputStream = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream serverOutputStream = new ObjectOutputStream(socket.getOutputStream());
Object object = serverInputStream.readObject();
while (scanner.hasNextLine()) {
out.println(scanner.nextLine());
serverOutputStream.writeObject(object);
}
}
}
I'm writing a java chat application using Multicast.
The clients can communicate among themselves but they can also send predefined messages to the server who always has the same answer to the respective predefined message.
Both client and server can receive and send messages. They are both subscribing recipients to the same host and port, so their sockets are the same, but when a client is sending a predefined message to the server, the server gets stuck in an infinite loop receiving the same message.
Code Server
final Lock lock = new ReentrantLock();
final Condition Rx = lock.newCondition();
final Condition Tx = lock.newCondition();
private volatile boolean msgRead;
private volatile int TypeMsg;
try{
NetworkInterface nif = NetworkInterface.getByName("en1");
MSocket = new MulticastSocket(port_chat);
group = InetAddress.getByName(adresse_chat);
MSocket.joinGroup(new InetSocketAddress(adresse_chat, port_chat), nif);
}catch(IOException se){
System.out.println(this.toString() + " IOException -> " + se.getMessage());
}
/*
Thread Rx
*/
new Thread(){
#Override
public void run(){
while(!isInterrupted()){
lock.lock();
try{
while(msgRead == true)
Rx.await();
byte[] buf = new byte[256];
DatagramPacket packetRx = new DatagramPacket(buf, buf.length);
try{
MSocket.receive(packetRx);
}catch(IOException ioe){
System.out.println(this.toString() + " IOException -> " + ioe.getMessage());
}
String received = new String(packetRx.getData(), 0, packetRx.getLength());
if("end".equals(received))
break;
if(received.contains("WEATHER_FORECAST") == true)
TypeMsg = 1;
else
if(received.contains("ASK_AGE_CAPTAIN") == true)
TypeMsg = 2;
msgRead = true;
Tx.signal();
}catch(InterruptedException ie){
System.out.println("Thread Rx -> " + ie.getMessage());
}
finally{
lock.unlock();
}
}
}
}.start();
/*
Thread Tx
*/
new Thread(){
#Override
public void run(){
while(!isInterrupted()){
lock.lock();
try{
while(msgRead == false)
Tx.await();
byte[] buf = new byte[256];
/* switch(TypeMsg){...} */
buf = text.getBytes();
DatagramPacket packetTx = new DatagramPacket(buf, buf.length, group, port_chat);
try{
MSocket.send(packetTx);
}catch(IOException ioe){
System.out.println(this.toString() + " IOException -> " + ioe.getMessage());
}
msgRead = false;
Rx.signal();
}catch(InterruptedException ie){
System.out.println("Thread Tx -> " + ie.getMessage());
}finally{
lock.unlock();
}
}
}
}.start();
Code Client
try{
NetworkInterface nif = NetworkInterface.getByName("en1");
MSocket = new MulticastSocket(port_chat);
group = InetAddress.getByName(adresse_chat);
MSocket.joinGroup(new InetSocketAddress(adresse_chat, port_chat), nif);
}catch(IOException se){
System.out.println(this.toString() + " IOException -> " + se.getMessage());
}
/*
Thread Rx
*/
new Thread(){
#Override
public void run(){
while(!isInterrupted()){
byte[] buf = new byte[256];
DatagramPacket packetRx = new DatagramPacket(buf, buf.length);
try{
MSocket.receive(packetRx);
}catch(IOException ioe){
System.out.println(this.toString() + " IOException -> " + ioe.getMessage());
}
String received = new String(packetRx.getData(), 0, packetRx.getLength());
if("end".equals(received))
break;
jTextArea_Rx.append(received + "\n");
}
}
}.start();
/*
Tx
*/
private void jButton_SendActionPerformed(java.awt.event.ActionEvent evt) {
byte[] buf = new byte[256];
String text = username + " >> " + jTextArea_Tx.getText();
buf = text.getBytes();
DatagramPacket packetTx = new DatagramPacket(buf, buf.length, group, port_chat);
try{
MSocket.send(packetTx);
}catch(IOException ioe){
System.out.println(this.toString() + " IOException -> " + ioe.getMessage());
}
}
This feels like it has something to do with the IP_MULTICAT_LOOP socket option which is surprisingly enabled by default in Java Multicast Sockets. Basically when this flag is enabled, you will receive messages you send on the multicast socket. So if you also send a message when you receive a message and you have this enabled, then you can create a loop.
Try disabling this socket option and see what happens.
I got it, I had to add
System.setProperty("java.net.preferIPv4Stack", "true");
at the beginning of the application and I also changed this part
try{
NetworkInterface nif = NetworkInterface.getByName("en1");
MSocket = new MulticastSocket(port_chat);
group = InetAddress.getByName(adresse_chat);
MSocket.joinGroup(new InetSocketAddress(adresse_chat, port_chat), nif);
}catch(IOException se){
System.out.println(this.toString() + " IOException -> " + se.getMessage());
}
to
try{
MSocket = new MulticastSocket(port_chat);
group = InetAddress.getByName(adresse_chat);
MSocket.joinGroup(group);
}catch(IOException se){
System.out.println(this.toString() + " IOException -> " + se.getMessage());
}
so no need to explicitly specifying the interface. I found the answer after some time here: Getting `Can't assign requested address` java.net.SocketException using Ehcache multicast
I am working on my assignment to make UDP reliable using java. How can i add Timeout and re-transmission to handle data-grams that are discarded and add Sequence numbers so the client can verify that a reply is for the appropriate request ??
this is client code
import java.net.*;
import java.io.*;
public class EchoClient {
// UDP port to which service is bound
public static final int SERVICE_PORT = 7;
// Max size of packet
public static final int BUFSIZE = 256;
public static void main(String args[]){
if (args.length != 1)
{
System.err.println ("Syntax - java EchoClient hostname");
return;
}
String hostname = args[0];
// Get an InetAddress for the specified hostname
InetAddress addr = null;
try
{
// Resolve the hostname to an InetAddr
addr = InetAddress.getByName(hostname);
}
catch (UnknownHostException uhe)
{
System.err.println ("Unable to resolve host");
return;
}
try
{
// Bind to any free port
DatagramSocket socket = new DatagramSocket();
// Set a timeout value of two seconds
socket.setSoTimeout (2 * 1000);
for (int i = 1 ; i <= 10; i++)
{
// Copy some data to our packet
String message = "Packet number " + i ;
char[] cArray = message.toCharArray();
byte[] sendbuf = new byte[cArray.length];
for (int offset = 0; offset < cArray.length ; offset++)
{
sendbuf[offset] = (byte) cArray[offset];
}
// Create a packet to send to the UDP server
DatagramPacket sendPacket = new DatagramPacket(sendbuf, cArray.length, addr, SERVICE_PORT);
System.out.println ("Sending packet to " + hostname);
// Send the packet
socket.send (sendPacket);
System.out.print ("Waiting for packet.... ");
// Create a small packet for receiving UDP packets
byte[] recbuf = new byte[BUFSIZE];
DatagramPacket receivePacket = new DatagramPacket(recbuf, BUFSIZE);
// Declare a timeout flag
boolean timeout = false;
// Catch any InterruptedIOException that is thrown
// while waiting to receive a UDP packet
try
{
socket.receive (receivePacket);
}
catch (InterruptedIOException ioe)
{
timeout = true;
}
if (!timeout)
{
System.out.println ("packet received!");
System.out.println ("Details : " + receivePacket.getAddress() );
// Obtain a byte input stream to read the UDP packet
ByteArrayInputStream bin = new ByteArrayInputStream (
receivePacket.getData(), 0, receivePacket.getLength() );
// Connect a reader for easier access
BufferedReader reader = new BufferedReader (
new InputStreamReader ( bin ) );
// Loop indefinitely
for (;;)
{
String line = reader.readLine();
// Check for end of data
if (line == null)
break;
else
System.out.println (line);
}
}
else
{
System.out.println ("packet lost!");
}
// Sleep for a second, to allow user to see packet
try
{
Thread.sleep(1000);
}catch (InterruptedException ie) {}
}
}
catch (IOException ioe)
{
System.err.println ("Socket error " + ioe);
}
}
}
What you can do is adding import TCP headers like sequence number, windows into the UDP message body to make it more like TCP. Here is the a solution that might help you.
I have posted my java proxy code below.
It works but it only gives me 1 server response instead of everything.
After the 1 response I just get client sent packets but with a size of 0.
Screenshots also attached.
Any ideas?
I've done some debugging. If I remove everything in between
typ = streamFromServer.readUnsignedShort();
siz = streamFromServer.readUnsignedShort();
siz <<= 8;
siz |= streamFromServer.readUnsignedByte();
byte[] dat = new byte[siz];
streamFromServer.readFully(dat, 0, siz);
String FullHe = DatatypeConverter.printHexBinary(dat);
System.out.println("Server sending data to Client:");
System.out.println("Type: " + typ + "");
System.out.println("Data Size: " + siz + "");
System.out.println("Full Data: " + FullHe + "");
System.out.println("\n\n");
Which is from the reading server response code it works and I get the client packets. How come it doesn't work with server packets?
Code:
import java.io.*;
import javax.xml.bind.DatatypeConverter;
import java.net.*;
public class proxy{
public static void main(String[] args) throws IOException {
//PrintStream out = new PrintStream(new FileOutputStream("log.txt"));
//System.setOut(out);
try{
String host = "gamea.clashofclans.com";
int remoteport = 9339;
ServerSocket ss = new ServerSocket(9339);
int localport = ss.getLocalPort();
ss.setReuseAddress(true);
// Print a start-up message
System.out.println("Starting proxy for " + host + ":" + remoteport
+ " on port " + localport);
// And start running the server
runServer(host, remoteport, localport,ss); // never returns
System.out.println("Started proxy!");
} catch (Exception e) {
System.out.println("Failed to start proxy" +e+ "");
}
}
public static void runServer(String host, int remoteport, int localport, ServerSocket ss)
throws IOException {
final byte[] request = new byte[2048];
byte[] reply = new byte[4096];
while (true) {
Socket client = null, server = null;
try {
System.out.println("Waiting for Client");
client = ss.accept();
System.out.println("Client Accepted!");
DataInputStream streamFromClient = new DataInputStream(client.getInputStream());
DataOutputStream streamToClient = new DataOutputStream(client.getOutputStream());
System.out.println("Connecting to server...");
// Make a connection to the real server.
server = new Socket("gamea.clashofclans.com", 9339);
System.out.println("Just connected client to " + server.getRemoteSocketAddress());
DataInputStream streamFromServer = new DataInputStream(server.getInputStream());
DataOutputStream streamToServer = new DataOutputStream(server.getOutputStream());
Thread t = new Thread() {
public void run() {
int bytesRead;
int type;
int size;
int version;
try {
while ((bytesRead = streamFromClient.read(request)) != -1) {
type = streamFromClient.readUnsignedShort();
size = streamFromClient.readUnsignedShort();
size <<= 8;
size |= streamFromClient.readUnsignedByte();
version = streamFromClient.readUnsignedByte();
byte[] data = new byte[size];
streamFromClient.readFully(data, 0, size);
String FullHex = DatatypeConverter.printHexBinary(data);
System.out.println("Client sending data to server:");
System.out.println("Type: " + type + "");
System.out.println("Data Size: " + size + "");
System.out.println("Version: " + version + "");
System.out.println("Full Data: " + FullHex + "");
System.out.println("\n\n");
streamToServer.write(request, 0, bytesRead);
streamToServer.flush();
}
} catch (IOException e) {
}
// the client closed the connection to us, so close our
// connection to the server.
try {
streamToServer.close();
} catch (IOException e) {
}
}
};
t.start();
int bytesRea;
int typ;
int siz;
try {
while ((bytesRea = streamFromServer.read(reply)) != -1) {
typ = streamFromServer.readUnsignedShort();
siz = streamFromServer.readUnsignedShort();
siz <<= 8;
siz |= streamFromServer.readUnsignedByte();
byte[] dat = new byte[siz];
streamFromServer.readFully(dat, 0, siz);
String FullHe = DatatypeConverter.printHexBinary(dat);
System.out.println("Server sending data to Client:");
System.out.println("Type: " + typ + "");
System.out.println("Data Size: " + siz + "");
System.out.println("Full Data: " + FullHe + "");
System.out.println("\n\n");
streamToClient.write(reply, 0, bytesRea);
streamToClient.flush();
}
} catch (IOException e) {
}
} catch (IOException e) {
System.err.println(e);
} finally {
try {
if (server != null)
server.close();
if (client != null)
client.close();
} catch (IOException e) {
}
}
}
}
}
This doesn't make sense. You're reading up to 4096 bytes from the server and then reading two type bytes and three length bytes and what you think is the request data, and writing what you read originally. So you're consuming the data about twice.
This can't work. You need to either just read the type, length, and value, and write them out again, or else, much more simply, just copy bytes from the input to the output, in both directions. (That way of course you can't do logging.)
NB Don't ignore IOExceptions, and especially not EOFExceptions when reading from DataInputStreams (or ObjectInputStreams).
Hi i have a problem with my server, everytime i call "dload" the file gets downloaded but i can't use the other commands i have because they get returned as null. Anyone who can see the problem in the code?
Server :
public class TCPServer {
public static void main(String[] args) {
ServerSocket server = null;
Socket client;
// Default port number we are going to use
int portnumber = 1234;
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
// Create Server side socket
try {
server = new ServerSocket(portnumber);
} catch (IOException ie) {
System.out.println("Cannot open socket." + ie);
System.exit(1);
}
System.out.println("ServerSocket is created " + server);
// Wait for the data from the client and reply
boolean isConnected = true;
try {
// Listens for a connection to be made to
// this socket and accepts it. The method blocks until
// a connection is made
System.out.println("Waiting for connect request...");
client = server.accept();
System.out.println("Connect request is accepted...");
String clientHost = client.getInetAddress().getHostAddress();
int clientPort = client.getPort();
System.out.println("Client host = " + clientHost
+ " Client port = " + clientPort);
// Read data from the client
while (isConnected == true) {
InputStream clientIn = client.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
clientIn));
String msgFromClient = br.readLine();
System.out.println("Message received from client = "
+ msgFromClient);
// Send response to the client
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("sum")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Double[] list;
list = new Double[5];
String value;
int i;
try {
for (i = 0; i < 5; i++) {
pw.println("Input number in arrayslot: " + i);
value = br.readLine();
double DoubleValue = Double.parseDouble(value);
list[i] = DoubleValue;
}
if (i == 5) {
Double sum = 0.0;
for (int k = 0; k < 5; k++) {
sum = sum + list[k];
}
pw.println("Sum of array is " + sum);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("max")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Double[] list;
list = new Double[5];
String value;
int i;
try {
for (i = 0; i < 5; i++) {
pw.println("Input number in arrayslot: " + i);
value = br.readLine();
double DoubleValue = Double.parseDouble(value);
list[i] = DoubleValue;
}
if (i == 5) {
Arrays.sort(list);
pw.println("Max integer in array is " + list[4]);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("time")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Calendar calendar = GregorianCalendar.getInstance();
String ansMsg = "Time is:, "
+ calendar.get(Calendar.HOUR_OF_DAY) + ":"
+ calendar.get(Calendar.MINUTE);
pw.println(ansMsg);
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("date")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Calendar calendar = GregorianCalendar.getInstance();
String ansMsg = "Date is: " + calendar.get(Calendar.DATE)
+ "/" + calendar.get(Calendar.MONTH) + "/"
+ calendar.get(Calendar.YEAR);
;
pw.println(ansMsg);
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("c2f")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
String celciusValue;
boolean ifRead = false;
try {
pw.println("Input celcius value");
celciusValue = br.readLine();
ifRead = true;
if (ifRead == true) {
double celcius = Double.parseDouble(celciusValue);
celcius = celcius * 9 / 5 + 32;
pw.println(celcius);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("dload")) {
OutputStream outToClient = client.getOutputStream();
if (outToClient != null) {
File myFile = new File("C:\\ftp\\pic.png");
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0,
mybytearray.length);
outToClient.flush();
outToClient.close();
bis.close();
fis.close();
} catch (IOException ex) {
// Do exception handling
}
System.out.println("test");
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("quit")) {
client.close();
break;
}
// if (msgFromClient != null
// && !msgFromClient.equalsIgnoreCase("bye")) {
// OutputStream clientOut = client.getOutputStream();
// PrintWriter pw = new PrintWriter(clientOut, true);
// String ansMsg = "Hello, " + msgFromClient;
// pw.println(ansMsg);
// }
// Close sockets
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("bye")) {
server.close();
client.close();
break;
}
msgFromClient = null;
}
} catch (IOException ie) {
}
}
}
Client:
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String args[]) {
boolean isConnected = true;
Socket client = null;
int portnumber = 1234; // Default port number we are going to use
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
try {
String msg = "";
// Create a client socket
client = new Socket("127.0.0.1", 1234);
System.out.println("Client socket is created " + client);
// Create an output stream of the client socket
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
// Create an input stream of the client socket
InputStream clientIn = client.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
clientIn));
// Create BufferedReader for a standard input
BufferedReader stdIn = new BufferedReader(new InputStreamReader(
System.in));
while (isConnected == true) {
System.out
.println("Commands: \n1. TIME\n2. DATE\n3. C2F\n4. MAX\n5. SUM\n6. DLOAD\n7. QUIT");
// Read data from standard input device and write it
// to the output stream of the client socket.
msg = stdIn.readLine().trim();
pw.println(msg);
// Read data from the input stream of the client socket.
if (msg.equalsIgnoreCase("dload")) {
byte[] aByte = new byte[1];
int bytesRead;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (clientIn != null) {
try {
FileOutputStream fos = new FileOutputStream("C:\\ftp\\pic.png");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = clientIn.read(aByte, 0, aByte.length);
do {
baos.write(aByte, 0, bytesRead);
bytesRead = clientIn.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
System.out.println("File is successfully downloaded to your selected directory"+ "\n" +"*-----------------*"+ "\n" );
} catch (IOException ex) {
System.out.println("Couldn't dowload the selected file, ERROR CODE "+ex);
}
}
}else{
System.out.println("Message returned from the server = "
+ br.readLine());
}
if (msg.equalsIgnoreCase("bye")) {
pw.close();
br.close();
break;
}
}
} catch (Exception e) {
}
}
}
debugged your code and have two hints:
1)
don't surpress your exceptions. handle them! first step would to print your stacktrace and this question on SO wouldn't ever be opened ;-) debug your code!
2)
outToClient.flush();
outToClient.close(); //is closing the socket implicitly
bis.close();
fis.close();
so in your second call the socket on server-side will already be closed.
first thing:
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
This can throw a NumberFormatException, and because args[0] is passed by the user you should handle this.
reading the code also this gave me a problem:
double DoubleValue = Double.parseDouble(value); // LINE 104
Throwing a NumberFormatException when I give c2f as command to the server. You definitively need to handle this exception anywhere in your code and give proper answer to the client, something like:
try{
double DoubleValue = Double.parseDouble(value);
}catch(NumberFormatException e){
// TELL THE CLIENT "ops, the number you inserted is not a valid double numer
}
(in short example, starting from this you have to enlarge the code)
while (isConnected == true) {
I cannot see it! why not use this?
while (isConnected) {
if (msgFromClient != null && msgFromClient.equalsIgnoreCase("sum")){
can be:
if("sum".equalsIgnoreCase(msgFromClient)){
in this case you have no problem with the NullPointerException. (if msgFromClient is null the statement is false).
By the way, date and time command are working fine for me. Check the others.
To fix dload i think you have to delete the line:
outToClient.close();
(EDIT: sorry to maxhax for the same answr, didn't see your answer while writing this)