Cannot getInputStream() in applet - java

Everyone,
I am trying to code an applet in Java which will access a video-game's Application Programming Interface (API), and while I can successfully run the applet via the Eclipse IDE, it consistantly hangs up when run from the browser.
I've narrowed down where the bug must be by scattering debug messages around until I found the last line run.
I am attempting to parse the output from a parameter-filled URL. Figuring browsers must pass this information differently than an IDE, I've tried many different methods of doing this, including POSTing the parameters via http socket (although I am unfamiliar with this method and could easily have implemented it incorrectly). Below is my current version, irrelevent parts omitted (if you should deduce the bug might be in an omitted area, these are easily revealed):
...
URL apiCharList = null;
...
try {
...
apiCharList = new URL("https:// ... ");
URLConnection connection = apiCharList.openConnection();
connection.connect();
DataInputStream in = new DataInputStream( new BufferedInputStream( connection.getInputStream() ) );
BufferedReader br = new BufferedReader( new InputStreamReader( in ) );
String line = br.readLine();
while( line != null ) {
...
line = br.readLine();
}
...
} catch (MalformedURLException e) {
current.setText( "Malformed URL" );
} catch (IOException e) {
current.setText( "InputStream fail." );
}
My debugging dropped me at:
connection.connect();
And without that line, at:
DataInputStream in = new DataInputStream( new BufferedInputStream( connection.getInputStream() ) );
Any insight into this problem is most appreciated. Again, simply let me know if/which omitted areas may be necessary to see.
Respectfully,
Inquiring
UPDATE
Thank you all for the replies. My BufferedReader now initializes as:
= new BufferedReader( new InputStreamReader( connection.getInputStream() ), 1 );
That part had been getting jumpbled up as a combination of all the various methods I had tried; thank you for ironing it out for me. From what I am seeing, it seems the issue is that my applet needs to be digitally signed in order to make the connections it requires when run via browser. I've been looking into that and have been having problems with keytool and jarsigner after downloading the latest JDK. I have only been at it for a short while, and have never had an applet digitally signed before, but at least I have a new avenue to pursue. If anyone caould provide a good (up to date) walkthrough on how to digitally sign an applet, that would be most appreciated. Various things I've read said it can cost me anywhere from 40USD to 20USD to nothing?
Anyways, thanks for the lift over this hurdle.
Respectully,
Inquiring

Browsers will not allow applets to make network connections anywhere but their own server of origin, by default. You would need to digitally sign the applet, then ask the user for permission to make the connection. An alternative is to run a simple proxy servlet on your web server which the applet can use to talk to the third-party server.
As an aside, why are you wrapping so many streams around eachother -- two of them buffered, which is a huge no-no -- just to read from the network? Those two lines could be replaced by
BufferedReader br = new BufferedReader( new InputStreamReader( connection.getInputStream() ), 1 );
Do note that ",1" I stuck in at the end, which turns off buffering for the BufferedReader. You do not want to read ahead on a network connection, or you're inviting your code to hang.

Related

BufferedReader doesn't receive string from LXSocket

i'm developing a simple test to connect via socket a java server application with an objective-c client side.
This is the java side:
BufferedReader dis = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = dis.readLine();
System.out.println("Message Received: " + message);
dis.close();
socket.close();
This is the objective-c side:
- (IBAction)click:(id)sender{
#try {
[socket sendString:[NSString stringWithFormat:#"%#",[toSend text]]];
}
#catch (NSException * e) {
NSLog(#"Unable to send data");
}
[toSend resignFirstResponder];
}
There are many problems:
in this way the output of server is:
Message Received: null
i read on this that readLine() needs to receive a string with "\n" that ends string, so i edit the line upon adding \n:
[socket sendString:[NSString stringWithFormat:#"%#\n",[toSend text]]];
but i retrieve an error on this line: EXC_BAD_ACCESS like in screenshot
What could be the problem? can someone help me?
I made a prototype in the Java side, and I don't have Objective-C/iOS or an Apple product.
I suspect the problem could be either in iOS or the Java side. So I hope you're sending text from iOS correctly.
Proposed code:
BufferedReader dis = new BufferedReader(new InputStreamReader(socket.getInputStream(), Charset.defaultCharset()));
The class InputStreamReader need a defined character set. The charset is supposed to be required, not optional! according to Sun documentation.
For expediency, pls just include more code for clean compile next time. Thanks.
Good luck n try it out!
Tommy Kwee
According to your modified post/question, you got an exception from the Objective-C side. So possibly the problem is not on the Java side.
For debugging purposes, I am proposing to make the C code simpler, like...
BOOL success;
success = [socket SendString: #"Hello World!"];
if (success != YES) {
NSLog(#"Fail to send")
}
Notes:
I am not familiar with Objective-C, and I could not find documentation from Apple on it. If you know, please tell me/us.
I did not use code "[toSend text]" because I did not find any references on it.
Other iOS developers are saying "%#" is meant for objects. Is code [toSend text] an object?
Finally, making a socket connection and achieving communication should be possible and not so hard, and eventually we'll get there. So let's do it!

What is the best way to code a Java TCP client (C# server)?

I have a server written in C# and need to talk to it from Java 1.6. I need to connect to the server, maintain the connection, and send messages in both directions. The messages are an int (length of the message) and then an XML file.
What is the best way to do this? I know Java well but I've never done TCP from Java (have done it from C#). So I have no idea what the best way to do this is. Speed is not an issue and simplicity is useful.
thanks - dave
So you want to build a Java client using Socket API. It's pretty simple to do.
try {
Socket socket = new Socket( host, port );
BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
PrintWriter out = new PrintWriter( new OutputStreamWriter( socket.getOutputStream() ) );
out.println("HELO");
String response = in.readLine();
System.out.println( response );
} finally {
in.close();
out.close();
socket.close();
}
Since you're only exchanging integers, you might want to use the classes Socket and DataOutputStream (for sending) and DataInputStream (for receiving).
I highly recommend to make the use of threads.
For starters, check out this tiny demo.
From there, the helpers provided by Apache Commons Net may clean up some of the lower-level work.

Processes locking on multicore machine

I recently started running my java program on my new multicore machine. I am suddenly seeing a problem which never occurred on my old single core Pentium. I suspect that the issue has to do with some sort of contention between my program and the various browsers I am running at the same time. When the processes get into this state, no amount of killing of processes seems to help (there's always some residual firefox or chrome process), so I end up restarting the machine. My program does a lot of opening and reading of URLs essentially using the following lines:
URL url = new URL( urlString );
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
........
while ((inputLine = in.readLine()) != null ) {...}
Every so often the URL my program tries to hit does not exist. In these cases, the call to create the BufferedReader eventually times out. I am going to modify the program to use a shorter time out, but I suspect that this in itself is not going to fix the problem.
Any suggestions would be appreciated.
I think the system change is a red herring. When you working with raw URL connection on the jdk there might be an issue. There is no in built retry mechanism and you will have to write all the code yourself. Try the HTTP client library from Apache. That should more or less solve any problem you face with URLConnection - http://hc.apache.org/httpclient-3.x/

using sockets to fetch a webpage with java

I'd like to fetch a webpage, just fetching the data (not parsing or rendering anything), just catch the data returned after a http request.
I'm trying to do this using the high-level Class Socket of the JavaRuntime Library.
I wonder if this is possible since I'm not at ease figuring out the beneath layer used for this two-point communication or I don't know if the trouble is coming from my own system.
.
Here's what my code is doing:
1) setting the socket.
this.socket = new Socket( "www.example.com", 80 );
2) setting the appropriate streams used for this communication.
this.out = new PrintWriter( socket.getOutputStream(), true);
this.in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
3) requesting the page (and this is where I'm not sure it's alright to do like this).
String query = "";
query += "GET / HTTP/1.1\r\n";
query += "Host: www.example.com\r\n";
...
query += "\r\n";
this.out.print(query);
4) reading the result (nothing in my case).
System.out.print( this.in.readLine() );
5) closing socket and streams.
If you're on a *nix system, look into CURL, which allows you to retrieve information off the internet using the command line. More lightweight than a Java socket connection.
If you want to use Java, and are just retrieving information from a webpage, check out the Java URL library (java.net.URL). Some sample Java code:
URL ur = new URL("www.google.com");
URLConnection conn = ur.openConnection();
InputStream is = conn.getInputStream();
String foo = new Scanner(is).useDelimiter("\\A").next();
System.out.println(foo);
That'll grab the specified URL, grab the data (html in this case) and spit it out to the console. Might have to tweak the delimiter abit, but this will work with most network endpoints sending data.
Your code looks pretty close. Your GET request is probably malformed in some way. Try this: open up a telnet client and connect to a web server. Paste in the GET request as you believe it should work. See if that returns anything. If it doesn't it means there is a problem with the GET request. The easiest thing to do that point would be write a program that listens on a socket (more or less the inverse of what you're doing) and point a web browser to localhost:[correct port] and see what the web browser sends you. Use that as your template for the GET request.
Alternatively you could try and piece it together from the HTTP specification.
I had to add the full URL to the GET parameter. To make it work. Although I see you can specify HOST also if you want.
Socket socket = new Socket("youtube.com",80);
PrintWriter out = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(socket.getOutputStream())));
out.println("GET http://www.youtube.com/yts/img/favicon_48-vflVjB_Qk.png
HTTP/1.0");
out.println();
out.flush();
Yes, it is possible. You just need to figure out the protocol. You are close.
I would create a simple server socket that prints out what it gets in. You can then use your browser to connect to the socket using a url like: http://localhost:8080. Then use your client socket to mimic the HTTP protocol from the browser.
Not sure why you're going lower down than URLConnection - its designed to do what you want to do: http://download.oracle.com/javase/tutorial/networking/urls/readingWriting.html.
The Java Tutorial on Sockets even says: "URLs and URLConnections provide a relatively high-level mechanism for accessing resources on the Internet. Sometimes your programs require lower-level network communication, for example, when you want to write a client-server application." Since you're not going lower than HTTP, I'm not sure what the point is of using a Socket.

java simple telnet client using sockets

I have read plenty of things on the topic, how telnet is a protocol, not a simple socket connection, waiting for newline characters, use of external libraries and whatnot...
The bottom line is that I need a quick and dirty java telnet application up and running, not necessarily scalable and not necessarily pretty, so I'm trying to avoid the use of libraries, system function calls and the like. I have been trying and testing and so far, when trying to log into a router (through telnet of course) I have got... nothing.
Here is a snipped of the code that I have been using so far, please someone point me at the right direction because I don't know what else I should try, because I'm certain that it has to be something really simple and silly that I'm missing. Thanks in advance!
Socket socket = new Socket("192.168.1.1", 23);
socket.setKeepAlive(true);
BufferedReader r = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter w = new PrintWriter(socket.getOutputStream(),true);
int c=0;
while ((c = r.read()) != -1)
System.out.print((char)c);
w.print("1234\r\n"); // also tried simply \n or \r
//w.flush();
//Thread.sleep(1000);
while ((c = r.read()) != -1)
System.out.print((char)c);
w.print("1234\r\n");
//Thread.sleep(1000);
while ((c = r.read()) != -1)
System.out.print((char)c);
socket.close();
It's hard to know what's wrong with your example without testing against your particular router. It might be a good idea to use a library, for instance http://sadun-util.sourceforge.net/telnet_library.html looks like an easy one to use.
Also this site says the following:
In order to carry on the conversation, a command is issued by simply sending it on the socket's outputstream (and using the telnet newline sequence \r\n):
String command="print hello";
PrintWriter pw = new PrintWriter(
new OutputStreamWriter(s.getOutputStream()), true);
pw.print(command+"\r\n");
If the session appears to hang after login, avoid to wrap the StreamWriter into a PrintWriter and instead run an explicit flush() at the end:
Writer w = new OutputStreamWriter(s.getOutputStream());
w.print(command+"\r\n");
w.flush();
This might actually be the problem with your code.

Categories