Finding Java server time and client time - java

I tried this code from this site server client code
It worked perfect on my machine,I first ran the server code then the client code.
And I got the time.
I tried putting the server side code on to another PC and running it on eclipse there,similarly I tried running client side code from eclipse on my side but wasn't successful.
It gave me the following error:
Exception in thread "main" java.net.BindException: Cannot assign requested address: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(Unknown Source)
at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
at java.net.PlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at sample.servertime.main(servertime.java:13)
Am I doing it correct or is it wrong what I am doing.Need help.
Here are the 2 codes.
// Date Client
import java.io.*;
import java.net.*;
class DateClient
{
publicstaticvoid main(String args[]) throws Exception
{
Socket soc=new Socket(InetAddress.getLocalHost(),5217);
BufferedReader in=new BufferedReader(
new InputStreamReader(
soc.getInputStream()
)
);
System.out.println(in.readLine());
}
}
// Date Server
import java.net.*;
import java.io.*;
import java.util.*;
class DateServer
{
publicstaticvoid main(String args[]) throws Exception
{
InetAddress locIP = InetAddress.getByName("192.168.1.21");
ServerSocket s= new ServerSocket(5217, 0, locIP);
while(true)
{
System.out.println("Waiting For Connection ...");
Socket soc=s.accept();
DataOutputStream out=new DataOutputStream(soc.getOutputStream());
out.writeBytes("Server Date" + (new Date()).toString() + "\n");
out.close();
soc.close();
}
}
}

In the server part you've hard coded the ip address for the server:
InetAddress locIP = InetAddress.getByName("192.168.1.21");
ServerSocket s= new ServerSocket(5217, 0, locIP);
When you run it on the other machine the address will be different and therefore it can't be bound unless you change it.
You could change it to bind to all addresses like:
ServerSocket s = new ServerSocket(5217);
Also, the client will always try to connect to the local machine:
Socket soc=new Socket(InetAddress.getLocalHost(),5217);
So if you want to have the client connect to a server on another machine InetAddress.getLocalHost()has to be changed to the address of the server.

Related

Simple SocketHandler for java8 logging(java.util.logging) throws ConnectionException

The intention is to stream the log during runtime on a specific host:port, so that the logs are accessible to users outside the running system, from browser.
As you can see, i have created a simple SocketHandler for java8 logging(java.util.logging), is there something that i have missed?
import java.net.MalformedURLException;
import java.net.URL;
import java.io.IOException;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.SocketHandler;
import java.util.logging.XMLFormatter;
public class Main {
public static void main(String[] args) throws Exception {
Logger logger = Logger.getLogger("concrete.log");
SocketHandler handler = new SocketHandler("HOSTNAME", 19004);
LogRecord logRec = new LogRecord(Level.INFO, "Log recorded");
handler.publish(logRec);
handler.setFormatter(new XMLFormatter());
logger.addHandler(handler);
logger.info("socket handler info message");
}
}
When i run the code, i see the following exception, i have tried checking the system firewall settings on both local(mac/windows) and remote(Linux) and seen that the settings do not block 19004 port
Exception in thread "main" java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:476)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:218)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:394)
at java.net.Socket.connect(Socket.java:606)
at java.net.Socket.connect(Socket.java:555)
at java.net.Socket.<init>(Socket.java:451)
at java.net.Socket.<init>(Socket.java:228)
at java.util.logging.SocketHandler.connect(SocketHandler.java:167)
at java.util.logging.SocketHandler.<init>(SocketHandler.java:154)
at Main.main(Main.java:16)
UPDATE
As suggested by bosowski
When i create Socket to listen to a specific port, the log messages are getting printed on the console of the host. However, am unable to access hostname:port for the log to be streamed from the browser. Is there anything specific that needs to be performed after this step?
Please let me know
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args)
{
try {
ServerSocket ss = new ServerSocket(19004);
Socket soc = ss.accept();
DataInputStream dis
= new DataInputStream(soc.getInputStream());
String str = (String)dis.readUTF();
System.out.println("message= " + str);
ss.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
SocketHandler does not open up a port to connect to, if that's what you're assuming. It tries to connect to the specified host and port, so you need to have a port that is listening on the host that you are trying to connect to.
https://docs.oracle.com/javase/8/docs/api/java/util/logging/SocketHandler.html#SocketHandler-java.lang.String-int-
<handler-name>.host specifies the target host name to connect to (no default).
<handler-name>.port specifies the target TCP port to use (no default).
If you do indeed have a listening TCP port on the hostname that you're trying to connect to, you can try running sudo nmap -F hostname to check if the port is indeed accessible from your machine.

Connection refused from client to server

I am learning about Sockets in Java and I am only missing how to receive back response from the server.
Following How to send string array object and How to send and receive serialized object in socket channel, I am trying to ask the user to pick as much as he wants out of choices:
1 - 2 - 3 - 4
And then I want to split and send them as an array to a server, where the server should send back the number of choices the user has picked.
For example if the user chose
2 3 4 1 2 3 4 1
Server should return
8
server is sending response fine, but on the client side I get error:
Exception in thread "main" java.net.ConnectException: Connection
refused: connect at java.net.DualStackPlainSocketImpl.connect0(Native
Method) at java.net.DualStackPlainSocketImpl.socketConnect(Unknown
Source) at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source) at
java.net.PlainSocketImpl.connect(Unknown Source) at
java.net.SocksSocketImpl.connect(Unknown Source) at
java.net.Socket.connect(Unknown Source) at
java.net.Socket.connect(Unknown Source) at
java.net.Socket.(Unknown Source) at
java.net.Socket.(Unknown Source) at
ClientClass.main(ClientClass.java:26)
I am not sure why the issue. Any help?
My Client:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
public class ClientClass {
public static void main(String args[]) throws IOException, ClassNotFoundException
{
// take order and convert it to array of choices
Scanner myScanner = new Scanner(System.in); // take from user
System.out.println("Enter all your choices seperated by space:");
System.out.println("Choices are: 1- 2- 3- 4");
String orderString = myScanner.next();
orderString += myScanner.nextLine();
String orderArray[] = orderString.split(" ");
// send request to server
Socket mySocket = new Socket("127.0.0.1", 4444); // create a socket
ObjectOutputStream out = new ObjectOutputStream(mySocket.getOutputStream());
out.writeObject(orderArray);
// get response from server
InputStream is = mySocket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
}
}
My Server:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
public class ServerClass {
public static void main(String args[]) throws IOException, ClassNotFoundException
{
// receive
ServerSocket myServerSocket = new ServerSocket(4444); // create a server socket
Socket mySimpleSocket = myServerSocket.accept(); // accept requests
ObjectInputStream ois = new ObjectInputStream(mySimpleSocket.getInputStream());
String[] choices = (String[]) ois.readObject();
// send back response
OutputStream os = mySimpleSocket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(choices.length);
System.out.println("Message sent to the client is "+choices.length);
bw.flush();
}
}
server is sending response fine
Rubbish. The server isn't even getting an incoming connection, let alone reading the request, let alone sending a response.
but on the client side I get error:
Exception in thread "main" java.net.ConnectException: Connection refused: connect at
On this evidence the server wasn't even running. Certainly not running in the same host as the client, which is what is required by new Socket("127.0.0.1", 4444).

Why is it showing me that connection has not established?

Why java is showing this output for every port connections And is it require any thing like basic frame or package in java other than these.i am working on basic server client program first is client and second is server.I tried basic code for only connection.but it shows this output every time
import java.io.*;
import java.net.*;
class DateClient
{
public static void main(String args[]) throws Exception
{
Socket soc=new Socket(InetAddress.getLocalHost(),5217);
BufferedReader in=new BufferedReader(new InputStreamReader(soc.getInputStream() ));
System.out.println(in.readLine());
}
}
import java.net.*;
import java.io.*;
import java.util.*;
class DateServer
{
public static void main(String args[]) throws Exception
{
ServerSocket s=new ServerSocket(5217);
while(true)
{
System.out.println("Waiting For Connection ...");
Socket soc=s.accept();
DataOutputStream out=new DataOutputStream(soc.getOutputStream());
out.writeBytes("Server Date: " + (new Date()).toString() + "\n");
out.close();
soc.close();
}
}
}
THIS IS OUTPUT
output:=
Exception in thread "main" java.net.ConnectException: Connection timed out: conn
ect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at DateClient.main(DateClient.java:8)
You are using the DNS resolver to get the local hostname, and you encounter a timeout when connecting to it, so:
either your DNS resolver is configured to a host that is down or filtered by a firewall,
or the DNS resolver resolves the local host name to an IP that is not the one of your server and is down or filtered by a firewall.
These are the two main cases for which you may have such a timeout, instead of a host unreachable or port unreachable error.
So, replace the line:
Socket soc = new Socket(InetAddress.getLocalHost(),5217);
by this one:
Socket soc = new Socket(InetAddress.getLoopbackAddress(), 5217);
to solve your problem.

Sending "227 \r\n" on port 21 terminates connection

Let me start off by stating that this is my first post here on stackoverflow. Feel free to point out any mistakes made while posting.
Okay, so the problem at hand is a little weird. I'm currently implementing the FTP protocol for my project, but ran into the following problem. Every time my application has to return the message "227 Entering Passive Mode (<ip1>,<ip2>,<ip3>,<ip4>,<port1>,<port2>)." the connection is terminated. The stack trace being:
java.net.SocketException: Software caused connection abort: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at sun.nio.cs.StreamEncoder.writeBytes(Unknown Source)
at sun.nio.cs.StreamEncoder.implFlushBuffer(Unknown Source)
at sun.nio.cs.StreamEncoder.implFlush(Unknown Source)
at sun.nio.cs.StreamEncoder.flush(Unknown Source)
at java.io.OutputStreamWriter.flush(Unknown Source)
at java.io.BufferedWriter.flush(Unknown Source)
at Server$1.run(Server.java:30)
at java.lang.Thread.run(Unknown Source)
In order to replicate the behaviour I decided to build a prototype which accepts a connection on port 21 and sends the message "227 " after recieving an arbitrary message from the client. This also results in the connection being terminated.
(Prototype Code snippet:)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
public void run() {
ServerSocket server = null;
try {
server = new ServerSocket(21);
} catch (IOException e1) {
e1.printStackTrace();
}
while(true) {
try {
Socket client = server.accept();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = null;
while((line = reader.readLine()) != null) {
writer.write("227 \r\n");
writer.flush();
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
}
(I'm aware the above code is not the nicest implementation, but is imho sufficiently adequate for representing the problem at hand.)
After some tinkering with the prototype I have figured out that this behaviour only occurs when sending "227 " in conjunction with using port 21 (e.g. using port 4500 works just fine).
Now of course the obvious workaround to this is to avoid using port 21, but i would like to know why i'm experiencing this. Any input on the matter is highly appreciated ;) (just to make sure, i'm using JavaSE-1.7).

Communicating to server in java to java

I know how to communicate with a server using a PHP script with JSON, but if the server was written in Java how would I communicate with the server using my Java program.
Would it be the same or is there some easier way that would exclude JSON?
The way I'm used to doing it is using a post request and then encoding/decoding in JSON
it is not a webserver
The most efficient way is to use Sockets. The tutorial does a good job of showing a client/server example.
you can use server socket programming as shown below
as client you can code like this
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String args[])
{
try
{
Socket server;
String str="";
DataInputStream d=new DataInputStream(System.in);
PrintStream toserver;
BufferedReader fromserver;
server=new Socket("117.198.219.36",1096); //your ip to connect and port no through which you will connect to server
InputStreamReader isr=new InputStreamReader(server.getInputStream());
fromserver= new BufferedReader(isr);
toserver=new PrintStream(server.getOutputStream());
while(true)
{
str=":"+d.readLine();
toserver.println(str);
str=fromserver.readLine();
System.out.println(str);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
this is client side program to send request .
Now the server side program is here below in this you will give same port number to connect to client.
import java.io.*;
import java.net.*;
public class Server
{
public static void main(String args[])
{
ServerSocket sc;
Socket client;
DataInputStream d;
PrintStream toClient;
BufferedReader fromClient;
String str="";
try
{
d=new DataInputStream(System.in);
sc=new ServerSocket(1096); //the same port no that we had given at client side
System.out.println("ServerStarted");
client=sc.accept();
InputStreamReader isr=new InputStreamReader(client.getInputStream());
fromClient=new BufferedReader(isr);
toClient=new PrintStream(client.getOutputStream());
while(true)
{
str=fromClient.readLine();
System.out.println(str);
str=":"+d.readLine();
toClient.println(str);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
try to use them you will be able to connect through this .i hope this will help you.
You can communicate as u want, but java developers preffer rpc ( http://en.wikipedia.org/wiki/Remote_procedure_call ) this is the easiest way implement by some frameworks, but if u need full controll of your messages u can do it thought json or even directly through socket (but i dont recommed to do this).

Categories

Resources