java server socket in cloud server - java

So I have two java classes for socket server and client as follows:
For the server:
System.out.println("Server started:");
ServerSocket server = new ServerSocket(1935, 0, InetAddress.getByName("localhost"));
Socket connection = new Socket();
while(active){
connection = server.accept();
printTimeStamp();
InputStream in = connection.getInputStream();
while(in.available() == 0){
//waiting till message is complete
}
MessageDecode(in);
}
MessageDecode is just an internal method that reads the input streams and stores it somewhere
for the client
Socket connectionSocket = new Socket();
InetAddress address = InetAddress.getByName("THE_CLOUD_SERVER_IP");
SocketAddress sAddress = new InetSocketAddress(address, 1935);
connectionSocket.setKeepAlive(true);
connectionSocket.setTcpNoDelay(true);
connectionSocket.connect(sAddress, 2000);
OutputStream os = connectionSocket.getOutputStream();
os.write("HELLO SERVER".getBytes());
os.close();
System.out.println("sent");
when I run both on a localhost it works like a charm, but when I run the class into the cloud server, I get timout exception java.net.SocketTimeoutException: connect timed out
even when the por is listening, I know its listening because when I run the app, and do a netstat -anp I get:
tcp 0 0 127.0.0.1:1935 0.0.0.0:* LISTEN PID/java
can someone give me a clue on how to solve this?
your help is must appreciated.
Thanks (._.')

As far as I know, cloud providers do not allow to open low level sockets (even WebSocket are rarely allowed). They usually use a proxy in front of the Java application server. Cloud providers are often used for HTTP application.
If you really want to use sockets, leave your current cloud provider and open an account on Amazon EC2.

Related

Java TCP Connection From Server through Client

How can a Server open a TCP connection through a Client which was connected to server before? Let say we have simple server like the code shows below; server waits for client connections and a handler thread serves connected clients. Client as below, every time wants to do an operation with the server, reestablish the connection, communicate with server and then close the connection. So, if server would like to open a TCP connection through the client(when there is no an active connection from client to server), how it can be done?
Server Code
public class DServer {
public static void main(String[] args) {
ServerSocket serverSocket = new ServerSocket(7800);
while(true) {
Socket socket = serverSocket.accept();
System.out.println("Server established a new connection");
HandleConnection handler = new HandleConnection(socket);
handler.start();
}
}
}
Client Code
public class DClient{
public static void main(String[] args) {
Socket socket = new Socket("localhost", 7800);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
//for every operation you do, first reestablish the connection,
//communicate with server, then close the connection.
}
}
I think you have some fundamental misunderstandings about what a client is and what a server is in a networking sense.
The server is the application listening for connections. The client is the application creating connections to the server. If you want both of your applications to be able to initiate communication at will, then your applications will need to be both clients and servers.
So your "DClient" application will need to have a ServerSocket. You "DClient" application can then inform your "DServer" application of it's host and port for when "DServer" wants to create a connection (note that things like NATing can make this sort of thing problematic if both applications are not in the same network).
Alternately, depending on your use case, you could just leave the connection from client to server open. This is the more usual approach to letting the server push data.
There is solution to create proxy server which is manage the both request client and server which called middleware for both client request.
In network programming it must required to fist server start and then client request because client server architecture.

How to run a simple socket server that allows incoming connections?

I am trying to build a very simple socket server in JAVA that my Flash application can listen to. I am using this tutorial. Everything seems to be working - the JAVA code is compiled and the server is running.
My question is: how can external applications send messages to this server using just an IP address and a port number? My goal is that flash can listen to socket messages sent by an external application.
The Java code:
import java.io.*;
import java.net.*;
class SimpleServer {
private static SimpleServer server;
ServerSocket socket;
Socket incoming;
BufferedReader readerIn;
PrintStream printOut;
public static void main(String[] args) {
int port = 8080;
try {
port = Integer.parseInt(args[0]);
} catch (ArrayIndexOutOfBoundsException e) {
// Catch exception and keep going.
}
server = new SimpleServer(port);
}
private SimpleServer(int port) {
System.out.println(">> Starting SimpleServer");
try {
socket = new ServerSocket(port);
incoming = socket.accept();
readerIn = new BufferedReader(
new InputStreamReader(
incoming.getInputStream()));
printOut = new PrintStream(incoming.getOutputStream());
printOut.println("Enter EXIT to exit.\r");
out("Enter EXIT to exit.\r");
boolean done = false;
while (!done) {
String str = readerIn.readLine();
if (str == null) {
done = true;
} else {
out("Echo: " + str + "\r");
if(str.trim().equals("EXIT"))
done = true;
}
incoming.close();
}
} catch (Exception e) {
System.out.println(e);
}
}
private void out(String str) {
printOut.println(str);
System.out.println(str);
}
}
Maybe I don't understand correctly your problem description, but if you create the server in Java, it listens to its port and not your Flash application. If you want your Flash application to wait for messages from other applications, it must have a server role and listen to a TCP port the same way as this Java server does.
You can connect to and test the given Java server easily by telnet program (available in all operating systems) by providing a host name or an IP address and a port as parameters:
telnet 127.0.0.1 8080
Any other application can connect in a similar way, using just a hostname/IP address and a port. For example in Java, you can create a client socket:
Socket clientSocket = new Socket("localhost", 8080);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
By not specifying an IP address for your socket, it will listen on 0.0.0.0 (all interfaces).
In fact, that will usually be your computer's IP / the server's IP.
Assuming that your application runs on your computer at home, there are three cases that cover most of the connection situations:
Connecting from the same machine:
Use 127.0.0.1:8080
Connecting from the same LAN (e.g. your brother's PC):
Use your LAN IP (e.g. 192.168.1.4:8080)
Connecting from WAN (outside your routers LAN) (internet e.g.):
Use your WAN IP.(e.g. 84.156.74.194). There are plenty websites, that tell you your WAN IP like this
You may have to setup your router, to forward the port 8080 to your PC
For simple connection tests, one could use a telnet client.
I think you are missing the point of client/server socket applications.
If you are building the socket server (with whatever programming language you chose), you will then need to connect with (a) socket client(s) to this server. After a connection is successfully established (persistent) between the client and the server, you can start what ever kind of communication you have implemented between them.
The server always acts as the passive, the client as active part in a socket server/client constellation.
I was checking the link that you are referring to. In that, the procedure to create a stand-alone server is mentioned which is the code that you have pasted as well.
According to the link, the application acts as the client and uses the XMLSocket methods to connect to this server. This application is the flash application that you are talking about. As mentioned in the link, by using the following code any flash application can connect and talk to the server:
var xmlsock:XMLSocket = new XMLSocket();
xmlsock.connect("127.0.0.1", 8080);
xmlsock.send(xmlFormattedData);
When you mention
My goal is that flash can listen to socket messages sent by an external application.
its actually the flash application that is the client and it cannot listen unless programmed to act as a server. I hope this provides some clarity!

Sending an object through a socket in grails using console Web GUI

I have two application servers in two Hosts. Each host has a Local address IP (172.x.x.x)
I want to send an object from 172.x.x.x:8080 to 172.y.y.y:8080 using Java sockets
Server Side(172.x.x.x:8080)
def myObject="Mar7ben bil World"
ServerSocket ss = new ServerSocket(8080);
Socket socket = ss.accept();
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject(myObject);
out.close();
Client Side(172.y.y.y:8080 )
Socket socket = new Socket('172.x.x.x',8080);
ObjectInputStream inp = new ObjectInputStream(socket.getInputStream());
Object o = inp.readObject();
obj= o;
inp.close();
socket.close();
i get the following error message when i run code of server side on console :
http://172.x.x.x:8080/myApp/console
java.net.BindException: Address already in use
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:383)
at java.net.ServerSocket.bind(ServerSocket.java:328)
at java.net.ServerSocket.<init>(ServerSocket.java:194)
at java.net.ServerSocket.<init>(ServerSocket.java:106)
Your Grails app listen 8080 port (http://172.x.x.x:8080/myApp/console). You have to change Server Side port to something else, 8081 for example.
P.S. 808x ports are usually used for HTTP services. If you aren't making a HTTP server, it's better to chose another port. See list of well-known ports: http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports

Why my chat application that does not work behind a router?

I developed a chat application Java/Socket(TCP), it works perfectly on my local network,however when i put it behind a router it does not work...
I have already tested the open ports on my router at:
http://www.yougetsignal.com/tools/open-ports/
the result is as follows
80 (HTTP)is open
21 (FTP)is open
22 (SSH)22 is open
23 (TELNET)is open
25 (SMTP)25 is open
.
.
.
I started my server with this list of ports(java -jar server.jar 23) :
int port=Integer.parseInt(args[0]);
ServerSocket serverSocket = null;
serverSocket = new ServerSocket(port);
System.out.println("server started at " + port);
Socket clientSocket = null ;
// repeatedly wait for connections, and process
while (true) {
try {
clientSocket = serverSocket.accept();
} catch (IOException ex) {
System.out.Println("error");
}
System.err.println("new client connected!");
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())),true);
String s;
while ((s = in.readLine()) != null) {
out.println("from server: "+s);
}
// colse all
out.close();
in.close();
clientSocket.close();
then Then with a simple client I tried to connect => anything received....
where does the problem? so how Skype,Msn and others chat application works fine?
there is a solution to do that ?
PS:I put a simple code(echo server) that represents my real server so you understand my code quickly :).
My regards .
This is just a guess, did you go into your router's configuration utility and set it up to proxy (usually called port forwarding) telnet requests to the client? Your router may be listening on 23, but unless you're running the chat client on the router's firmware, I doubt it knows what to do with that traffic. Maybe I misunderstood your question though.
Just having a server running behind a router is not enough for an outside client to establish a connection. Whatever port the server is listening on, the router needs to have a Port Forwarding rule configured on it that forwards inbound traffic for that port to the machine the server is running on. The client then needs to connect to the port on the router's public IP so the router can then forward that traffic to the server.

Sockets in Java...?

I need to build an application which can receive data from over a network and use this data to do some unrelevant things with.
Here's a piece of code to make clear what I'm doing.
On the server side:
static Socket client = null;
static ServerSocket ss = null;
if (ss != null) {
ss.close();
}
ss = new ServerSocket(5513);
isrunning = true;
System.out.println("Waiting for client...");
client = ss.accept();
System.out.println("Client accepted.");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
And the client side:
Socket client = null;
PrintWriter out = null;
try {
client = new Socket("hostname", 5513);
out = new PrintWriter(client.getOutputStream(), true);
}
Please note that this is just a piece of the code. There are no errors in the code.
After running the server-sided piece of code, it correctly waits for the client to connect.
Now here comes the problem. As soon as I try to connect from the client side, I'm getting a "connection refused"-error.
HOWEVER, I found something on the internet whoch told me to try telnetting from the client side. For example, let the server-sided IP be 192.168.1.1. So, after using this command:
telnet 192.168.1.1 5513
I actually get a connection with the server. The command will launch an empty screen, and everything I manually type in the command line will be sent to the server-side after pressing enter (checked with debugging).
So, I can manually connect to the server-side and send some data, but my code refuses to connect.
Anyone who knows what I am doing wrong?
Is this the code you're actually using?
client = new Socket("hostname", 5513);
Try changing it to:
client = new Socket("192.168.1.1", 5513);
client = new Socket("hostname", 5513);
Hostname needs to represent the IP Address you're connecting to. If you're trying to connect to yourself, it would be "localhost"
Also, the server is not listening for the client AT ALL TIMES, there must be a while loop so the server listens and accepts connections.
while (true) {
client = ss.accept();
out = new PrintWriter(client.getOutputStream(), true);
//You should probably assign it to a seperate thread to handle stuff for this client
}
And I should explain on why you're getting that particular error. When something says that the connection is refused, it usually means that the IP Address you want to connect to knows your sending a connection and is blocking it because it was not listening for that connection. Basically, when the server closed, you stopped listening for the client, so anything that came in on that port would be blocked. Of course, the other case could be that Java was blocked on your firewall and an exception should be made for it. Although this is rarely the case if what you're trying to accomplish is over a LAN.
You're not actually using "hostname" in your Socket object in the client are you?
It should the 192.168.1.1.
Are you on Windows? and If so have you added java.exe and javaw.exe to Firewall with inbound and outbound enabled? and have you added a rule for 5513 to your Firewall?
If yes Windows but no Firewall settings, that's your answer, open up your Firewall.

Categories