How to verify the ACE-CORBA service local windows machine - java

I'm able to create docker container for ACE-TAO service , and able to access it from parent windows machine using port-forwarding concept.
From browser i try to hit the localhost:forward-port and getting "ERR_EMPTY_RESPONSE" and TAO service is running in docker container.
If I want to verify in local, whether its connected properly or not.
How can I write Java code to verify?

The following java code connects to localhost:17500 and prints out a message saying whether or not it could create a tcp connection.
import java.io.*;
import java.net.*;
class TCPClient
{
public static void main(String argv[]) throws Exception
{
try {
Socket clientSocket = new Socket("localhost", 17500);
System.out.println("Could connect");
}
catch (ConnectException e) {
System.out.println("Cannot connect");
}
}
}

Related

Connection refused error when using sockets between C# (server) and Java (Client) applications

I am trying to create a socket connection between a .Net server application and Java Client Application.
I am getting an error from the java client application:
Connection refused: connect
Notes:
Communicating with a .Net Client Application, works fine.
I have disables the windows firewall
Undoubtedly, I am running the server application in the background and then I am running the client application
Following are my server code (C#):
public class Server
{
public Server()
{
CreateListener();
}
public void CreateListener()
{
// Create an instance of the TcpListener class.
TcpListener tcpListener = null;
IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
string output;
try
{
// Set the listener on the local IP address
// and specify the port.
tcpListener = new TcpListener(ipAddress, 13);
tcpListener.Start();
output = "Waiting for a connection...";
}
catch (Exception e)
{
output = "Error: " + e.ToString();
MessageBox.Show(output);
}
}
}
and client application code (Java):
public class smtpClient {
public void Send() {
Socket smtpSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
try {
smtpSocket = new Socket("localhost", 13); // FAILURE
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host: hostname");
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
It fails at the following line in the Java Client Application:
smtpSocket = new Socket("localhost", 13);
I can't tell what is the issue you are facing, but you need to start with a solid foundation to discover these issues.
As a rule of thumb, you should always write one piece (typically the server) first and verify connectivity (say using telnet) and then write the other piece (typically client) and verify its connectivity.
I always keep a Standard Client and Server handy to test whether its my code or its the environment/configuration.
Below is a sample code that works fine to test connectivity.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
class ClientServer {
static void Main() {
new Thread(() => { StartServer("localhost", 5013); }).Start();
Thread.Sleep(100);
Console.WriteLine("\nPress enter to start the client...");
Console.ReadLine();
StartClient("localhost", 5013);
}
public static void StartServer(string serverInterface, int port) {
try {
IPHostEntry hostInfo = Dns.GetHostEntry(serverInterface);
string hostName = hostInfo.HostName;
IPAddress ipAddress = hostInfo.AddressList[0];
var server = new TcpListener(ipAddress, port);
server.Start();
Console.WriteLine($"Waiting for a connection at {server.LocalEndpoint}");
Console.WriteLine("Press ctrl+c to exit server...");
while (true) {
TcpClient client = server.AcceptTcpClient();
Console.WriteLine($"Server says - Client connected: {client.Client.RemoteEndPoint}");
ThreadPool.QueueUserWorkItem((state) => {
using (var _client = (TcpClient)state)
using (NetworkStream stream = _client.GetStream()) {
string msg = stream.ReadAsciiData();
if (msg == "Hello!") {
stream.WriteAsciiData($"Time:{DateTime.Now: yyyy/MM/dd HH:mm zzz}. Server name is {hostName}");
}
}
}, client);
}
} catch (Exception e) {
Console.WriteLine(e);
}
}
public static void StartClient(string serverInterface, int port) {
Console.WriteLine("Client started...");
try {
using (var client = new TcpClient(serverInterface, port))
using (NetworkStream stream = client.GetStream()) {
Console.WriteLine("Client says - Hello!");
stream.Write(Encoding.ASCII.GetBytes("Hello!"));
string msg = stream.ReadAsciiData();
Console.WriteLine($"Client says - Message from server: Server#{client.Client.RemoteEndPoint}: {msg}");
}
} catch (Exception e) {
Console.WriteLine(e);
}
Console.WriteLine("Client exited");
}
}
static class Utils {
public static void WriteAsciiData(this NetworkStream stream, string data) {
stream.Write(Encoding.ASCII.GetBytes(data));
}
public static string ReadAsciiData(this NetworkStream stream) {
var buffer = new byte[1024];
int read = stream.Read(buffer, 0, buffer.Length);
return Encoding.ASCII.GetString(buffer, 0, read);
}
public static void Write(this NetworkStream stream, byte[] data) {
stream.Write(data, 0, data.Length);
}
}
Now to your specific problem,
The choice of port 13, is not ideal for testing. Usually all ports below 1024 are considered privileged. i.e. a firewall or antivirus might block your attempt to listen on that port
Remember that IPV6 addresses plays a role. Your machine might have that enabled or disabled based on your configuration. You want to make sure that if your server is listening on a IPv6 interface, then your client also connects on the same
Which brings us to another related point: Irrespective of you are using IPv6 interface or not, the client needs to connect to the same interface the server is listening on. This might seem obvious, but is often missed. A typical machine
has at-least 2 interfaces: One for localhost (127...* called loopback interface) and another non local (typically 10...* or 192...*, but not restricted to it). It can so happen (especially when you pick the first available interface to bind your server without knowing which one it is) that server might be listening on non loopback interface like say 192.168.1.10 interface and the client might be connecting to 127.0.0.1, and you can see why the client will get "connection refused" errors
The sample code above works and you can test your code with it. You can us telnet for a client or just my sample code. You can play around changing the serverInterface values to some surprising discoveries which are accentuated by
ipAddress = hostInfo.AddressList[0] line
Hope this helps you with your debugging

Client-Server connects while being on the same computer but not while being run on different ones

I'm trying to build a basic client-server application.
When I run both the server and the client on the same computer both manage to connect without a hitch but if I try to do so from different computers (desktop and laptop) the connection doesn't get though. The server isn't even aware that someone tried to connect to it while the client timeouts after a while. At first I assumed that it's a firewall problem but disabling the firewall completely on the server PC did not help. Tried changing ports and checked on multiple computers. Any ideas what could cause this?
I control both the server and the client and can change the code of both if necessary. The server always runs on the same PC and I'm connecting to it directly using hardcoded IP address.
This is the code of the client sending random int to the server.
public static void main(String[] args) {
Socket s = new Socket();
try {
s.connect(new InetSocketAddress("123.45.67.891", 8084), 5000);
s.getOutputStream().write(42);
s.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
}
The server is slightly more complicated but considering the fact that they manage to connect while being run from the same PC I assume that the problem isn't with it.
edit: Server code (Thread per client. There shouldn't be too many of those)
public void run() {
try {
serverSocket = new ServerSocket(listenPort); //integer
} catch (IOException e) { ... }
while (shouldRun) {
try {
Socket clientSocket = serverSocket.accept(); // Blocked here while trying to connect from remote computer
//Never gets here
ConnectionHandler newConnection = connectionHandlerCreator.create(clientSocket);
connectionHandlers.add(newConnection);
newConnection.initialize();
new Thread(newConnection).start();
} catch (IOException e) { ... }
}
}
Initialize consists of the following (which latter used for I/O).
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
The problem is probably on your server side though: you have to make it respond to all ip's not just local one, by using the constructor:
ServerSocket(int port)
it will default accepting connections on any addresses which is not the case if you specified an IP

RMI cannot connect to remote server

I've been plying with RMI recently and while I managed to make it work on locahost I've been having all sorts of problem when trying to use a remote server. Here's the basic code I'm trying to run:
Server:
public class RmiServer extends UnicastRemoteObject implements RmiServerIntf {
public static final String MESSAGE = "Hello world";
public RmiServer() throws RemoteException {
}
public String getMessage() {
return MESSAGE;
}
public static void main(String args[]) {
System.out.println("RMI server started");
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
System.out.println("Security manager installed.");
} else {
System.out.println("Security manager already exists.");
}
try {
LocateRegistry.createRegistry(1099);
System.out.println("java RMI registry created.");
} catch (RemoteException e) {
e.printStackTrace();
}
try {
RmiServer obj = new RmiServer();
Naming.rebind("rmi://localhost/RmiServer", obj);
System.out.println("PeerServer bound in registry");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Remote class interface:
public interface RmiServerIntf extends Remote {
public String getMessage() throws RemoteException;
}
Client:
public class RmiClient {
RmiServerIntf obj = null;
public String getMessage() {
try {
obj = (RmiServerIntf)Naming.lookup("rmi://54.229.66.xxx/RmiServer");
return obj.getMessage();
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
public static void main(String args[]) {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
RmiClient cli = new RmiClient();
System.out.println(cli.getMessage());
}
}
rmi.policy file:
grant {
permission java.security.AllPermission;
};
I compiled the classes and created a stub for the server. Then I placed client, stub, interface and policy on my machine and server, stub, interface and policy on the remote machine. The remote server being a Linux machine I made all the files executable. I also added a rule on the local firewall allowing port 1099, and opened all ports on the remote machine
After this I navigated to the server's directory on the remote machine and inserted the following command:
java -Djava.security.policy=rmi.policy RmiServer
This didn't give me problems so I went back to the local machine and entered
java -Djava.security.policy=rmi.policy RmiClient
I wait, and wait and I get the error message:
Connection refused to host: 172.31.xx.xx; nested exception is: java.net.ConnectException: Connection timed out: connect
I've been fighting with these connection errors all day yesterday and this is as far as I got. I'm sure there's only one very small thing I'm still doing wrong but I just can't find what it is.
This may not solve your problem, but I've had similar issues with JPPF (via Java RMI) on Linux. The solution was to ensure that the ephemeral port range on the Client-side machine covered only ports that were allowable by the Client-side's local firewall. E.g., if your firewall allows ports 48000 to 64000 to be connected to by an external machine, ensure that your ephemeral port range also falls within 48000 to 64000. Give that a try and let us know what happens.
System.setProperty("java.rmi.server.hostname","10.0.3.73");
Please use the above statements in your RMIServer side code, and try and connect from remote client again. It worked for me

how to run java tcp server in window azure?

how to run java tcp server in window azure?
can window azure do it?
I find so many article about java application for window azure,they is that open a JSP web project in eclipse, and than use worker role publish it in window azure, but my tcp server is general java project, so how to publish it to window azure?
my tcp server:
public class test {
private static int serverport = 12345;
private static ServerSocket serverSocket;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(serverport);
System.out.println("Server is start.");
while (!serverSocket.isClosed()) {
System.out.println("Wait new clinet connect!");
waitNewPlayer();
}
} catch (IOException e) {
System.out.println("Server Socket ERROR");
}
}
public static void waitNewPlayer() {
try {
Socket socket = serverSocket.accept();
System.out.println(socket.getInetAddress().getHostAddress()+"'s socket is connected now!");
createNewUser(socket);
} catch (IOException e) {
}
}
public static void createNewUser(final Socket socket) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
out.println("nangnang");
} catch (IOException e) {
System.out.println("Socket is closed!");
}
System.out.println("This socket is removed form the player array!");
}
});
t.start();
}
}
You should be able to run an app like this in Azure, but you'll need to take care of a couple of things:
Open an Input Endpoint for your worker role - this opens the port to the outside world. You then need to either map it to the exact same port internally, or let Azure pick a port for you (and then you can ask the role environment which port you've been assigned, and open that port in your code instead of 12345)
For all your println's, you'd need to remote-desktop to see them, or you need to push them to diagnostics logging so you can see those debug statements via an external tool like Cerebrata's Diagnostics Manager.
As far as publishing: It's the same as the jsp examples you've seen: you build an Azure project to go along with your Java project, you set up the role size and instance count, create input endpoints, optionally create a cache, set up configuration settings for storage accounts, create a package to run in emulator or in the cloud, etc.
You might also want to try AzureRunMe which also supports Azure Java Project. http://azurerunme.codeplex.com/

How to make communication between one server and multiple client in Java Socket Programming?

I have two java applications, one is web app and another is simple java app, So I am using Socket programming for communication between them.
I made one SocketServer which is a Thread, in which I created ServerSocket serverSocket = new ServerSocket(6789)
And in my web app I created Socket client = new Socket("localhost", 6789);
My server sends some data to client and client will start some other work, but if I want to run another client i.e. server will send different parameters and client have to start processing what should I do?
Because server is already started on '6789' port and first client also with the same port. How can I start client with another port?
Every time Server must have to started first and then client.
I think client will not found server till both are having same ports.
Am I have to create another server instance with different port and then invoke client??? But How can my client will know on which port server is started?
For Example:
Imagine I have UI like:
start MIlind
start xyz
start abc
and click on strart it will call client and start process, If an start Milind first then How will I start xyz?
because 'start Milind' started client and server at port 6789, How will other start process works?
It seems like a lot of overhead to create a server/client app just for a web app to communicate with a local java program (and even more so to duplicate this process to do more than one thing at a time). If you are looking for concurrent processing in the background of a web app, you can always just create a thread (or multiple threads) to do the work. Or is there a reason why the simple java app can't be embedded in the web app?
You need to split off threads when accepting your socket connections server side. This is very easily done with serversocket. A very rudimentary (untested!) implementation:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
class Server {
private ServerSocket socket;
public Server() {
try {
this.socket = new ServerSocket(6789);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void go() throws IOException {
while(true) {
Socket sock = socket.accept();
new Thread(new ClientSession(sock)).start();
}
}
public static void main(String[] args) {
Server server = new Server();
try {
server.go();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class ClientSession implements Runnable {
private final Socket clientsocket;
ClientSession(Socket sock) {
this.clientsocket = sock;
}
#Override
public void run() {
//do stuff, like read from socket.
}
}
}
Note that you don't need to change the port at all.

Categories