There is an existing service that i would like to write a dummy service (using Netty) for. It will be used for testing purposes.
The existing client code fragment for the service looks like:
Socket socket = new java.net.Socket();
socket.connect(new InetSocketAddress("localhost", 8080), 10000);
socket.setSoTimeout(20000); // set a timeout of 20 seconds
InputStreamReader ir = new InputStreamReader(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// write some string to the server and wait for answer
out.println("SomeCommand");
// server has written some answer, read it
char[] c = new char[2];
ir.read(c, 0, 2);
String cs = new String(c);
if ("OK".equals(cs.toString())) {
// write some more string's to the server
}
// we're done, close the connection
out.println("BYE");
out.close();
socket.close();
Is Netty the right framework to create a server for java.net.Socket connections? (If not, which framework should be used, if any?)
I am trying to find a way to start with Netty using the QuoteOfTheMoment example. The QuoteOfTheMomentServerHandler does basically what i want, upon the incoming message, return some answer so that the above snippet can read the answer using the inputstream but the above socket cannot make a connection to the QuoteOfTheMomentServer. The error is "connection refused".
[EDIT] More clarification:
The problem (i think) is not connecting or the port i use. Let me try to better ask the question:
I just started with netty (no nio experience) and am not familiar with the different types of channels, pipelines and what not.
The server should, like a servlet request/response (like, not http or trying to rebuild a http servlet impl), react on a inputString written to the output-stream as in the code fragment and write back some string/bytes to the input-stream as in the code fragment, so the client only then moves on. So the connection should stay open but also be synchronous, the client waits for answer from the server. If i use the example "Writing the Server Side of a Socket" in the java tutorial i am able to get it working for the client. But i want to utilize the thread handling etc. from netty.
The QuoteOfTheMomentServerHandler seems as server side implementation what i want but can that setup handle the given client code ?
So the question is which kind of pipeline, channel or something like that should be used given the way the client works ?
Again, the client and server are existing. I want to build a dummy server implementation to work with the existing client.
Netty is a TCP/IP framework. So yes if you are developing a TCP/IP server this toolkit is good to use.
I assume you are getting a error when trying to connect the client to the server. Also the server should also be running.
When getting a the connection refused error there are a couple of thine to check. First one is the firewall(if any) on the server allowing connections to port 8080? Secondly from your client machine try open a telnet session to the server something like:
Telnet yourserverip 8080
This opens a socket connection to the server. If you get a error message Google it.
The last one is that you might be running a server like tomcat, glassfish, IIS which uses port 8080 already. Try a non standard port like 10810 for example.
UPDATES:
If you are new to netty please read the users guide found here http://netty.io/docs/stable/guide/html/.
I had a look at the Quote of the moment service and I do believe I found part of the problem. The Quote of the moment service is a broadcast UDP/IP client and server. UDP is a much more lightweight "version" of TCP IP. It does not guarantee delivery to the client or server and it is broadcast. UDP is sort of like a radio broadcast as it is generally not targeted to a specific IP but broadcast over the entire network. Thus you normal TCP IP connection will not be able to work on the UDP server.
See this link on how to write a UDP Client http://systembash.com/content/a-simple-java-udp-server-and-udp-client/.
I would suggest that you convert the Quote of the moment server from UDP to TCP/IP server as this will give you some practise in creating a TCP/IP server without getting into too much detail. Once you are comfortable with that you should be able to start once from scratch.
Just remember that Netty handles the NIO part for you. It is a higher level framework based on NIO thus hiding a lot of the detail from you. You dont need to know NIO that well to use netty but you need to understand the Netty concepts well.
Related
Is it possible to connect to a server like "www.google.com" for example server side. Not actually connecting through google.com but that is the idea.
ServerSocket serverSocket = new ServerSocket(0, 50, InetAddress.getByName("www.google.com"));
This code returns null, I am new to this connection related stuff so I don't know exactly what that would be meaning.
This is the code I have currently for setting up the server, it works fine when using localhost, but I am unsure on how to continue with an actual domain and server so anyone can connect and communicate.
If it isn't possible to set up a server like that, what is the best way to implement and I am trying to do.
you can open raw sockets to whatever you want, but a ServerSocket is if you want to be a server, not if you want to connect to one; you'd use normal Socket for that.
sockets is for raw TCP/IP. You run some service on top of it. For example, HTTP or HTTPS, which is what the web runs on, is built on top of it.
I really doubt you want to write an HTTP client just for www.google.com, it's rather complicated. Fortunately, java has one built in. Don't use Socket, use HttpClient.
See the java HTTP client tutorial here.
I have to write a Socket communication program to implement
Inter Process Communication.
I understand I need to have a client and server implementation.
Server implementation:
MyServerice = new ServerSocket(PortNumber);
Client and server will be on same machine so I don't want to interfere with any other running applications
How to decide which port number to use?
You can look at this table
those are mostly all, you will never know if any other external app is taking the port you have in mind, so in your case is a
Firt to come, first to serve issue
I think in implementing the websocket object, the WebSocket protocol communications typically use TCP port number 80, so environments that block non-standard internet connections by using a firewall will still pass WebSocket packets.
I have not worked with HTTP post/get before, my up coming project in my office is based on http post/get in java. Its basically client - server based application. the client will post some info and I need to get that info and process the string and vice-verse. this project has to be developed on J2SE. You can assume this some thing like a JMS queue message processing stuff. I googled for the info but most of the information was for web application, mine should work like a message queue. Can someone explain me how to do this or point me where I can get some useful info.
Thanks
Arun
Well, if you don't need to specifically use strict HTTP, and you need to just use Java SE (and not Java EE, which rules out Servlets, JSPs, JMS, etc), then you need to probably investigate ServerSocket and Socket classes.
Server
Your server would need to listen on a TCP port (say, port 8080) - usually you would pick a port number between 1025 and 65,535, however if you are attempting to use an already defined service that has a default port, then use that. Note however, that on unix, in order to listen on any port below 1024, I believe you need to be root. Traditionally, port 80 is used for HTTP.
To listen on this port, you would need something like this in your code:
ServerSocket srvSocket = new ServerSocket(8080);
Socket socket = srvSocket.accept();
This pretty much the most basic code that would cause your application to wait until something connected to port 8080. Once connected, you could obtain both an InputStream and OutputStream for your connected client, by interrogating the returned socket object, allowing you to read content from the client, and inserting these requests in a queue. This queue could be then processed by some other Thread.
Client
In order for your client to connect to the server, you would need to use something based on the following example:
Socket connection = new Socket("server.domain.com", 8080);
OutputStream output = connection.getOutputStream();
You would then write your request to the server into the OutputStream (and read from the InputStream returned from getInputStream() if you expected a response)
The code supplied is pretty basic, but it should give you a rough idea of how to proceed. You can even use this method if you wanted to use real HTTP, however it might be a better idea to use some premade library if that was the case (although its probable that you're not going to require all functionality defined in the HTTP spec itself).
Anyway, I hope that provides you a good starting point from which to build.
Jetty is a popular web server, designed to easily be embedded in an application.
Its HTTP server component can run inside your application and respond to requests by dispatching to your custom code.
Jetty also features an HTTP client that you can use on the client side to send requests.
This is a rather big topic and I won't be able to post a complete guide, but Jetty's documentation is generally of very high quality and should be a good starting point.
I suggest you start with learning the basics of HTTP protocol. This article is a good starter. After you understood the basics follow the this article on how to programatically communicate (read/write) with HTTP servers. After that Google is your friend.
If you weren't restricted to J2SE, you could use Servlets for managing the POST/GET methods of HTTP. Evaluate if it is possible, otherwise you'd be reinventing the wheel
I also have a mainly SE background. On the client side, writing get/post is pretty easy. Or you can Google to find source code. I found that using REST was straightforward and understandable. On the server side, there are many options and I have very limited experience. I wrote the server using standard JEE6 and it wasn't too painful, but sounds like that is not an option for you.
I have 4 phones connected to a Wifi access point and I know the MAC/IP of all of these including the Wifi access point.
I need to implement communication between each of these phones, a sort of peer to peer communication, I was thinking about using sockets but then each phone will have to implement a ServerSocket and Socket on each of the phones is this fine?
The Ip's of these phones would be in private range 192.168.... so could I use something like http://192.168.xx.xx/port and contact any phone using http? What kind of classes could I use to implement this, or is there a ready framework that I could directly use?
What you are planning is just fine: you can have phones listen on sockets too. If you just want to have peer-to-peer communication and are more interested in the application you're writing, you might want to take a look at JXTA, which is a somewhat popular P2P system for Java. I don't know it, and I've heard some bad things about its performance, but for your application it could be suitable.
But it's not very hard to roll your own, either. However, I haven't seen any HTTP server-side libraries for Java ME, so using HTTP might be more work than necessary. I would probably just implement a custom protocol over TCP sockets, since it does not appear you would need to be interoperable with anything already in existence.
Socket communication in Java ME is through the Generic Connection Framework, found in the javax.microedition.io package, and from the client side it's exactly like using HTTP connections, i.e., something like
String url = "socket://192.168.xxx.xxx:12345";
SocketConnection conn = (SocketConnection) Connector.open(url);
And then you can get an InputStream and OutputStream for the connection from that, or DataInputStream and DataOutputStream if you want to send binary data.
On the server side you would do
String url = "socket://:12345";
ServerSocketConnection sock = (ServerSocketConnection) Connector.open(url);
SocketConnection conn = (SocketConnection) sock.acceptAndOpen();
The acceptAndOpen blocks until a connection is made, so if it is important for the server to be doing something else, make sure to put the connection acceptance into its own thread.
A caveat: when I was doing this a few years back, I found out that just listening on a socket does not turn on the network on all phones, so even though the server began listening, it was not possible to connect to it because it was not on the network. The way I worked around it was to open the Web browser on the phone, but any client opening a socket is enough, so you could also do it from the application by trying to open a client connection yourself.
There is also something called the Push Registry. When you create your Midlet, there is a possibility to register the application with a MIDlet-Push attribute in the JAD file, so that you don't have to have your application running but the system will wake it up when a connection is attempted on a certain port. I've never actually implemented this, so I cannot give any more advice on it.
I'm a bit confused. I would like to send messages from my Red5 Server to my Flash App... but I don't find any information how to do that...
Can anyone help me?
This looks like a good start:
http://www.red5tutorials.net/index.php/Tutorials:Getting_Started_With_Red5_Server
See near the bottom for their simple flash client.
Edit: More options given now that it's clear we're going from server-client:
Looks like you need to do something like this:
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/NetConnection.html
and
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/NetStream.html
which would mean using "NetStream.play()" to get the server to stream data to the client.
Or you might want to look at the Socket class(es) and manually create a direct socket connection between the client and server.
Keep in mind here, I've never used Red5. Just trying to help :)
For anyone who didn't find an answer until today: I am working in red5, and you can send message from red5 to flash by a RemoteSharedObject in AS3 connecting to a sharedobject in red5.
Server Code:
ISharedObject so = getSharedObject(scope, "chat");
so.setAttribute("message","Welcome");
Client Code:
so = SharedObject.getRemote("chat", connection.uri, false);
so.connect(connection);
so.addEventListener(SyncEvent.SYNC, syncChatHandler);
private function syncChatHandler(event:SyncEvent):void {
Alert.show(so.data.message,"Information");
}
This code will show an alert on users connected with the message "Welcome". From here read a lot of documentation and use your imagination.
Hmm, by definition, the server serves and the client requests. So to create a push scenario, you still have to first initialize a connection from the client to the server. Then you can leave the connection idle until you need to send something to the client. Polling is the other method, where the server holds on to the messages and the client frequently checks in to see if new messages are available. A server cannot initiate a connection to the client. That would make the client a server. In other words, you could have the flash client register it's current IP with the server and open up a port itself, establishing itself as a server. Then the Red5 server becomes a client and can connect to the server inside the flash client. But I imagine many security restrictions will prevent your flash program from acting as a server in the real world.