Java Networking

Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.

Moderator: Coders of Rage

Post Reply
ajtgarber
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 97
Joined: Wed Jun 10, 2009 8:56 am

Java Networking

Post by ajtgarber »

Code: Select all

import java.net.*;
import java.io.*;
import java.util.*;

public class TestClient extends Object {
	public static void main(String[] args) {
		try {
			Socket socket = new Socket("localhost", 80);
			PrintStream ps = new PrintStream(socket.getOutputStream(), true);
			ps.println("send test.txt");
			ps.println("4");
			ps.println("test");
			ps.close();
		} catch(Exception ex) {
			ex.printStackTrace();
		}
	}
}
For some reason when this client connects to the server I wrote, my server gets the "send test.txt" and it gets the "4" but it just drops "test" completely, I tried sending the exact same information to my server in telnet and it worked fine, I have no idea whats going wrong
User avatar
Kleithap
ES Web Developer
ES Web Developer
Posts: 324
Joined: Sat Jan 26, 2008 9:03 am
Location: Amsterdam

Re: Java Networking

Post by Kleithap »

Try flushing the output stream using ps.flush(). If that doesn't work I dunno, maybe post the server code as well.
ajtgarber
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 97
Joined: Wed Jun 10, 2009 8:56 am

Re: Java Networking

Post by ajtgarber »

Doesn't the close method also flush the stream?
User avatar
Kleithap
ES Web Developer
ES Web Developer
Posts: 324
Joined: Sat Jan 26, 2008 9:03 am
Location: Amsterdam

Re: Java Networking

Post by Kleithap »

ajtgarber wrote:Doesn't the close method also flush the stream?
Hmm yeah, that is the specified behaviour, but maybe an error occurred or something. Check http://stackoverflow.com/questions/2208 ... t-flushing, could that have something to do with your problem? Could you post the server code?

EDIT: Also, is their any particular reason why you're explicitly extending the Object class? All classes are implicitly subclasses of Object.

EDIT 2: Just to check, I wrote some extremely simple and ugly server code, and your clients seems to run fine against it. The problem may not lie with the client but with the server. Here's the ugly code that works:

Code: Select all

import java.net.*;
import java.io.*;
import java.util.*;

public class TestServer extends Object {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8080);;
            Socket clientSocket = null;
            String inputLine;
            
            clientSocket = serverSocket.accept();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                                                clientSocket.getInputStream()));
            
            while ((inputLine = in.readLine()) != null) {
                System.out.printf("Read: %s\n", inputLine);
            }


        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }
}
ajtgarber
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 97
Joined: Wed Jun 10, 2009 8:56 am

Re: Java Networking

Post by ajtgarber »

Server:

Code: Select all

import java.net.*;
import java.io.*;
import java.util.*;

public class FileServer extends Object {
	public static void main(String[] args) {
		try {
			ServerSocket serverSocket = new ServerSocket(80);
			System.out.println("Listening for connections on port 80...");
			while(true) {
				Socket socket = serverSocket.accept();
				System.out.println("Connection received! "+socket.getInetAddress());
				
				Service service = new Service(socket);
				service.start();
			}
		} catch(Exception ex) {
			System.out.println("Exception Raised! Exiting...");
			System.out.println();
			
			ex.printStackTrace();
		}
	}
} class Service extends Thread {
	protected Socket socket;
	protected PrintStream ps;
	protected Scanner scan;
	
	public Service(Socket socket) throws Exception {
		this.socket = socket;
		ps = new PrintStream(socket.getOutputStream());
		scan = new Scanner(socket.getInputStream());
	}
	
	public void run() {
		try {
			InputStream is = socket.getInputStream();
			OutputStream os = socket.getOutputStream();
			
			while(true) {
				String request = scan.nextLine();
				
				if(request.toLowerCase().startsWith("request ")) {
					String file = request.substring(7, request.length()).trim();
					
					FileInputStream fis = new FileInputStream(new File(file));
					
					byte[] bytes = new byte[fis.available()];
					while(true) {
						int b = fis.read(bytes);
						if(b == -1 || b == 0) break;
						ps.write(bytes);
						bytes = new byte[fis.available()];
					}
					fis.close();
					ps.flush();
					System.out.println("Request Complete!");
				} else if(request.equalsIgnoreCase("list")) {
					String list = "";
					String[] files = new File("./").list();
					for(int i = 0; i < files.length; i++) {
						list += files[i];
						if(i != files.length-1) list += ", ";
					}
					ps.println(list);
					ps.flush();
					System.out.println("Done Listing!");
				} else if(request.toLowerCase().startsWith("send ")) {
				//issues
					String placement = request.substring(4, request.length()).trim();
					int num = scan.nextInt();
					System.out.println(num);
					File file = new File(placement);
					FileOutputStream fos = new FileOutputStream(file);
					for(int i = 0; i < num; i++) {
						byte b = (byte)is.read();
						System.out.print(b);
						fos.write(b);
					}
					System.out.println("Finished Writing File!");
					fos.flush();
					fos.close();
				} else {
					socket.close();
					break;
				}
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			try { socket.close(); } catch(Exception ex2) {}
		}
	}
}
I'm not really sure why I explicitly extended Object *shrugs*
ajtgarber
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 97
Joined: Wed Jun 10, 2009 8:56 am

Re: Java Networking

Post by ajtgarber »

When I called checkError() on ps in TestClient it returned false, its definitely the server then :P.

Code: Select all

...
else if(request.toLowerCase().startsWith("send ")) {
            //issues
               String placement = request.substring(4, request.length()).trim();
               int num = scan.nextInt();
               System.out.println(num);
               File file = new File(placement);
               FileOutputStream fos = new FileOutputStream(file);
               for(int i = 0; i < num; i++) {
                  byte b = (byte)is.read();
                  System.out.print(b);
                  fos.write(b);
               }
               System.out.println("Finished Writing File!");
               fos.flush();
               fos.close();
}
...
^ The issue should be in there, (yes I know thats not the most efficient way to read from the network but right now I'm just
trying to get it to work...). The call to is.read() always returns -1.
wearymemory
Chaos Rift Junior
Chaos Rift Junior
Posts: 209
Joined: Thu Feb 12, 2009 8:46 pm

Re: Java Networking

Post by wearymemory »

I understand that this is a bit late, but I believe the problem you have experienced here is due to the Scanner class. Your client has called PrintStream#println, thus writing 4, followed by a newline character. Your server uses Scanner#nextInt in order to retrieve the value 4, but that method does not take the newline character that was written to the stream. This causes your next invocation of the Scanner#nextLine method to end on that leftover newline character, returning an empty String. You've chosen to close your client's connection to the server if no valid argument has been supplied, and that is why -1 is returned from your calls to InputStream#read afterward.

You could simply put

Code: Select all

scan.nextLine();
under your call to Scanner#nextInt.
Post Reply