Java server , client program - java

The code below should allow the user to enter a URL and have it return the ip address of that website but it's not working.
The application is a console application. I had it working at one time but I don't know why it won't work now.
Here is the error i am getting when the users enters a website to get the ip address from
IOException: java.net.SocketException: Connection reset
HERE IS MY CLIENT CODE
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
String hostname = "localhost";
int port = 6052;
if (args.length > 0) {
hostname = args[0];
}
Socket clientSocket = null;
PrintWriter os = null;
BufferedReader is = null;
try {
clientSocket = new Socket(hostname, port);
os = new PrintWriter(clientSocket.getOutputStream(), true);
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + hostname);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: " + hostname);
}
if (clientSocket == null || os == null || is == null) {
System.err.println("Something is really wrong. ");
return;
}
try {
if (args.length != 2) {
System.out.print("Enter a www web address (must have www!) ");
BufferedReader br = new BufferedReader(new InputSreamReader(Sy.in))
String keyboardInput = br.readLine();
os.println(keyboardInput);
} else {
os.println(args[1]);
}
String responseLine = is.readLine();
System.out.println("The IP address of " + args[1] + "is" + responseLine);
} catch (UnknownHostException e) {
System.err.println("Trying to connect to host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
HERE IS MY SERVER CODE
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String args[]) {
int port = 6052;
Server server = new Server(port);
server.startServer();
}
ServerSocket echoServer = null;
Socket clientSocket = null;
int numConnections = 0;
int port;
public Server(int port) {
this.port = port;
}
public void stopServer() {
System.out.println("Server working hold on a min.");
System.exit(0);
}
public void startServer() {
try {
echoServer = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Server is now started and is waiting for Clients.");
while (true) {
try {
clientSocket = echoServer.accept();
numConnections++;
new Thread(new ServerConnection(clientSocket, numConnections,
this)).start();
} catch (IOException e) {
System.out.println(e);
}
}
}
}
class ServerConnection implements Runnable {
private static BufferedReader is;
private static PrintStream os;
private static Socket clientSocket;
private static int id;
private static Server server;
public ServerConnection(Socket clientSocket, int id, Server server) {
this.clientSocket = clientSocket;
this.id = id;
this.server = server;
System.out.println( "Connection " + id + " established with: " + clientSocket );
try {
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
os = new PrintStream(clientSocket.getOutputStream());
} catch (IOException e) {
System.out.println(e);
}
}
public void run() {
String line;
try {
boolean serverStop = false;
line = is.readLine();
System.out.println( "Received " + line + " from Connection " + id + "." );
InetAddress hostAddress = InetAddress.getByName(line);
String IPaddress = hostAddress.getHostAddress();
os.println(IPaddress);
is.close();
os.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

With no arguments, host will be localhost, user will be propted for a website. ArrayOutOfBoundsException because you didn't check the arguments.
With one argument, it is the host. Passing a site will not work because the site won't work as expected.
Running with two arguments, it works if the first argument is localhost.

Related

Java basic concurrent communicator - does not fully accept connection

I want to create simple communicator with one server and few clients who could connect and send data to it. It works fine without any threads, with only one client, but once i try to incorporate concurrency it doesn't work. From client perspective there is some connection, I can send data, but there is no sign of receiving that data on server. Here is the server class:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class MyServerSocket implements Runnable
{
private ServerSocket serverSocket;
public MyServerSocket() throws Exception
{
Random generator = new Random();
this.serverSocket = new ServerSocket(generator.nextInt(65000 - 60000) + 60000, 50, InetAddress.getByName("192.168.0.105"));
}
public InetAddress getSocketIPAddress()
{
return this.serverSocket.getInetAddress();
}
public int getPort()
{
return this.serverSocket.getLocalPort();
}
public void run()
{
while (true)
{
System.out.println("Running a thread");
try
{
String data = null;
Socket client = this.serverSocket.accept();
String clientAddress = client.getInetAddress().getHostName();
System.out.println("Connection from: " + clientAddress);
System.out.println("Here I am");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
String message = "";
while ((data = in.readLine()) != null && data.compareToIgnoreCase("quit") != 0)
{
message = ("\r\nMessage from " + clientAddress + ": " + data);
System.out.println(message);
out.write(message);
}
} catch (Exception e)
{
System.out.println("Something went wrong");
} finally
{
try
{
serverSocket.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
Server main:
import java.lang.Thread;
public class Main
{
public static void main(String[] args)
{
try
{
MyServerSocket socket = new MyServerSocket();
Runnable runnable = new MyServerSocket();
System.out.println("Port number: " + socket.getPort() + " IP address: " + socket.getSocketIPAddress());
Thread thread = new Thread(runnable);
thread.start();
}catch (Exception e)
{
e.printStackTrace();
}
}
}
Client class:
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class ClientSocket
{
private Socket socket;
private Scanner scanner;
ClientSocket(InetAddress serverAddress, int serverPort) throws Exception
{
this.socket = new Socket(serverAddress, serverPort);
this.scanner = new Scanner(System.in);
}
public void sendData() throws Exception
{
String data;
System.out.println("Please type in the message. If you want to terminate the connection, type Quit");
PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true);
do
{
data = scanner.nextLine();
out.println(data);
out.flush();
}while(data.compareToIgnoreCase("quit") != 0);
out.println();
}
}
Client main:
import java.net.InetAddress;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int port;
System.out.println("Provide port at which you will communicate with the server");
port = scanner.nextInt();
try
{
ClientSocket socket1 = new ClientSocket(InetAddress.getByName("192.168.0.105"), port);
socket1.sendData();
}catch(Exception e)
{
System.out.println("Could not connect to the server.");
}
}
}
Server somehow stops its working when is about to accept the client connection, while client works fine and seem to be connected to the server.
In server side, once you accept a client connection, you should new a thread to process this connection:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class MyServerSocket implements Runnable {
private ServerSocket serverSocket;
public MyServerSocket() throws Exception {
Random generator = new Random();
this.serverSocket = new ServerSocket(generator.nextInt(65000 - 60000) + 60000, 50, InetAddress.getByName("192.168.0.105"));
}
public InetAddress getSocketIPAddress() {
return this.serverSocket.getInetAddress();
}
public int getPort() {
return this.serverSocket.getLocalPort();
}
public void run() {
while (true) {
System.out.println("Running a thread");
try(Socket client = this.serverSocket.accept()) {
// new thread to process this client
new Thread(() -> {
try {
String data = null;
String clientAddress = client.getInetAddress().getHostName();
System.out.println("Connection from: " + clientAddress);
System.out.println("Here I am");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
String message = "";
while (true) {
if (!((data = in.readLine()) != null && data.compareToIgnoreCase("quit") != 0)) break;
message = ("\r\nMessage from " + clientAddress + ": " + data);
System.out.println(message);
out.write(message);
}
} catch (IOException e) {
System.out.println("Something went wrong");
}
}).start();
} catch (Exception e) {
System.out.println("Something went wrong");
}
}
}
}
Ok, somehow I solved that problem, but still I need to understand how does it work:
Accepting connection inside try block, without finally block (nor try with resources) so socket is opened all the time.
Modified main method so there is no threads or runnable objects at all in it. The whole process is done within the class:
Code:
public class Main
{
public static void main(String[] args)
{
try
{
MyServerSocket socket = new MyServerSocket();
System.out.println("Port number: " + socket.getPort() + " IP address: " + socket.getSocketIPAddress());
socket.run();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
If anyone could point me out mistakes that are still in this final version of code I'll be grateful.

How to Create a Backup Server in TCP Java Application,

I have a Java application that has a TCP Server and It handles the client requests. Now I want to create a TCP backup Server, so that when the TCP Server Fails, the backup server continues from the point the TCP Server failed and Handle the client request.
How this can be done?
I have a client and a server.
This is my code for TCP Server for now..
import java.net.*;
import java.io.*;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public class TCPServer {
static ScriptEngineManager mgr;
static ScriptEngine engine;
public static void main(String args[]) {
mgr = new ScriptEngineManager();
engine = mgr.getEngineByName("js");
try {
int serverPort = 7896; // the server port
ServerSocket listenSocket = new ServerSocket(serverPort);
while (true) {
System.out.println("Server is ready and waiting for requests .... ");
Socket clientSocket = listenSocket.accept();
System.out.println("request received from client with IP : " + clientSocket.getInetAddress());
System.out.println("port of client : " + clientSocket.getPort());
Thread c = new Connection(clientSocket);
}
} catch (IOException e) {
//if already in use then redirect the request to backup server
System.out.println("Listen socket:" + e.getMessage());
}
}
}
class Connection extends Thread {
DataInputStream in;
DataOutputStream out;
Socket clientSocket;
public Connection(Socket aClientSocket) {
try {
clientSocket = aClientSocket;
in = new DataInputStream(clientSocket.getInputStream());
out = new DataOutputStream(clientSocket.getOutputStream());
this.start();
} catch (IOException e) {
System.out.println("Connection:" + e.getMessage());
}
}
public void run() {
//send client request to bacckup server, with client IP adddress and port number
//BackupTCPServer bus = new BackupTCPServer();
//bus.clientIP = clientSocket.getInetAddress();
//bus.clientPort = clientSocket.getPort();
//System.out.println(bus);
try {
String s = in.readUTF();
//bus.Expressionsbackup.add(s);
String exp = "";
int res = 0;
while (s != null) {
TCPServer.engine.put("i", 2);
TCPServer.engine.put("j", 4);
exp =s;
Object result = TCPServer.engine.eval(exp);
double st = (Double)result;
out.writeUTF(Double.toString(st));
//bus.expressionevaluated++;
s = in.readUTF();
}
}
catch (ScriptException se) {
System.out.println("SE:" + se.getMessage());
}
catch (EOFException e) {
System.out.println("EOF:" + e.getMessage());
} catch (IOException e) {
System.out.println("readline:" + e.getMessage());
} finally {
try {
clientSocket.close();
} catch (Exception e) {
/*close failed*/
}
}
}
}

Server not receiving input from client

I have a server and client. My problem is that when the client writes messages, the server is not receiving the messages.
Server code
public class BankServer {
private int port;
private BufferedReader reader = null;
private PrintWriter writer = null;
public BankServer(int port)
{
this.port = port;
}
public void startServer() {
print("Contact server at: " + getServerAddress() + ": port: " + port);
while(true) {
try {
ServerSocket ss = new ServerSocket(port);
Socket client = ss.accept();
if(client != null) {
print("Client connected");
}
reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
writer = new PrintWriter(client.getOutputStream(), true);
String msg = null;
print("Server waiting for input");
while((msg = reader.readLine()) != null) {
print("Printer: " + msg);
writer.write(msg);
}
client.close();
ss.close();
closeStreams();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void closeStreams() {
if(reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
} }
if(writer != null) {
writer.close();
}
}
private String getServerAddress() {
InetAddress inetAdr = null;
try {
inetAdr = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
String host = inetAdr.getHostAddress();
return host;
}
public void print(String msg) {
System.out.println(msg);
}
public static void main(String[] args) {
new BankServer(2222).startServer();
}
}
I have this code, where the Server waits for input:
ServerSocket ss = new ServerSocket(port);
Socket client = ss.accept();
if(client != null) {
print("Client connected");
}
From this code, I can see that a connection is made. But when client sends messages, they are not printed by the server
Here is the client code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class BankClient {
private PrintWriter writer = null;
private BufferedReader reader = null;
private Socket socket;
private int port;
private String adr;
public BankClient(String address, int port)
{
adr = address;
this.port = port;
try {
socket = new Socket(adr, this.port);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeMsg(String msg) {
try {
while((msg = reader.readLine()) != null) {
writer.print("From client: " + msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
BankClient client = new BankClient("127.0.0.1", 2222);
Scanner scanner = new Scanner(System.in);
System.out.println("Waiting for input");
while(true) {
String msg = scanner.nextLine();
client.writeMsg(msg);
if(msg.equals("quit")) {
System.out.println("Bye");
break;
}
}
scanner.close();
}
}
This is the first time I work with streams, and I am also pretty new to programming. I have found a lot of help on stackoverflow, and google, but I just can't figure this out.
Thanks for any help you can provide
Replace :
public void writeMsg(String msg) {
try {
while((msg = reader.readLine()) != null) {
writer.print("From client: " + msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
By :
public void writeMsg(String msg) {
try {
DataOutputStream outToServer = new DataOutputStream(socket.getOutputStream());
outToServer.writeBytes("From client: " + msg + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
Client Side:
Server Side :
Change
writer.print("From client: " + msg);
to
writer.println("From client: " + msg);
and remove the while((msg = reader.readLine()) != null) at the client.
EDIT: And you have to add writer.flush();. That worked for me.
EDIT2: The complete solution. Change BankClient here:
public void writeMsg(String msg) {
writer.println("From client: " + msg);
writer.flush();
}

Java IO socket not sending outputstream

When debugging my code, the code stops here:
while (( msg = reader.readLine()) != null) {
writer.write("From server: " + msg);
}
I am sending input from a client class, but I can't figure out where I am wrong, since the server never receives the message.
Here is my entire sever class:
import java.io.*;
import java.net.*;
public class Server {
private BufferedReader reader;
private PrintWriter writer;
private int port;
public Server(int port)
{
this.port = port;
}
private String getSeverAddress() {
String host = null;
try {
InetAddress adr = InetAddress.getLocalHost();
host = adr.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return host;
}
public void startServer() {
print("Contact this sever on address: " + getSeverAddress() + " port: " + port);
ServerSocket ss = null;
Socket socket = null;
try {
ss = new ServerSocket(port);
socket = ss.accept();
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream(), true);
String msg = null;
while (( msg = reader.readLine()) != null) {
writer.write("From server: " + msg);
print(msg);
if(msg.toLowerCase().equals("Bye")) {
print("Client left");
break;
}
}
ss.close();
socket.close();
reader.close();
writer.close();
} catch(SocketException e) {
e.printStackTrace();
} catch (IOException i ) {
i.printStackTrace();
return;
}
}
private void print(String msg) {
System.out.println(msg);
}
public static void main(String[] args) {
Server server = new Server(1111);
server.startServer();
}
}
And here is the client class:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client {
private Socket client;
private BufferedReader reader;
private PrintWriter writer;
public Client(Socket socket)
{
client = socket;
try{
reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
writer = new PrintWriter(client.getOutputStream(), true);
} catch (Exception e) {
e.printStackTrace();
}
}
public void writeToServer() {
print("Write message to server");
String msg = null;
try {
while((msg = reader.readLine()) != null) {
writer.write("From client: " + msg);
print(msg);
if(msg.toLowerCase().equals("quit")) {
break;
}
}
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void print(String msg) {
System.out.println(msg);
}
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket("localhost", 1111);
} catch (Exception e) {
e.printStackTrace();
}
Client client = new Client(socket);
client.writeToServer();
}
}
Your mistake is server and client both sending/receiving messages background without printing anything. Like when you send message from client, Server received it and again write to the client and it become infinite loop.
Following things are wrong:
Server.java
try {
while (( msg = reader.readLine()) != null) {
print(msg);
if(msg.toLowerCase().equals("bye")) {
print("Client left");
break;
}
writer.write("From server: " + msg);
}
Should be the last statement of loop writer.write("From client: " + msg); and if(msg.toLowerCase().equals("Bye")) should bye
Client.java
try {
while((msg = reader.readLine()) != null) {
print(msg);
if(msg.toLowerCase().equals("quit")) {
break;
}
writer.write("From client: " + msg);
}
It should be last in loop writer.write("From client: " + msg);
You're reading lines but you aren't sending lines. You need to send a line terminator.

Why it is refusing the connection for second time?

I am trying to forward a message from a client to a server and again from that server to another server. For the first time it works fine but when I type second message its say "Unexpected exception: Connection refused" why is it so?
Here is the code
Client.java
import java.net.*;
import java.io.*;
public class Client {
private Socket socket = null;
private DataInputStream console = null;
private DataOutputStream streamOut = null;
#SuppressWarnings("deprecation")
public Client(String serverName, int serverPort) {
System.out.println("Establishing connection. Please wait ...");
try {
socket = new Socket(serverName, serverPort);
System.out.println("Connected: " + socket);
start();
} catch (UnknownHostException uhe) {
System.out.println("Host unknown: " + uhe.getMessage());
} catch (IOException ioe) {
System.out.println("Unexpected exception: " + ioe.getMessage());
}
String line = "";
while (!line.equals("exit")) {
try {
line = console.readLine();
streamOut.writeUTF(line);
streamOut.flush();
} catch (IOException ioe) {
System.out.println("Sending error: " + ioe.getMessage());
}
}
}
public void start() throws IOException {
console = new DataInputStream(System.in);
streamOut = new DataOutputStream(socket.getOutputStream());
}
public void stop() {
try {
if (console != null)
console.close();
if (streamOut != null)
streamOut.close();
if (socket != null)
socket.close();
} catch (IOException ioe) {
System.out.println("Error closing ...");
}
}
public static void main(String args[]) {
#SuppressWarnings("unused")
Client client = null;
if (args.length != 2)
System.out.println("Usage: java Client host port");
else
client = new Client(args[0], Integer.parseInt(args[1]));
}
}
AuServer.java
import java.net.*;
import java.io.*;
public class AuServer {
private Socket socket = null;
private Socket publishingsocket = null;
private ServerSocket server = null;
private DataInputStream streamIn = null;
private String line = null;
private DataOutputStream streamOut = null;
public AuServer(int port) {
try {
System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted: " + socket);
open();
boolean done = false;
while (!done) {
try {
line = streamIn.readUTF();
System.out.println(line);
done = line.equals("exit");
} catch (IOException ioe) {
done = true;
}
forward(line, 50090);
}
close();
} catch (IOException ioe) {
System.out.println(ioe);
}
}
public void forward(String line, int port) {
try {
publishingsocket = new Socket("localhost", port);
streamOut = new DataOutputStream(publishingsocket.getOutputStream());
streamOut.writeUTF(line);
streamOut.flush();
} catch (UnknownHostException uhe) {
System.out.println("Host unknown: " + uhe.getMessage());
} catch (IOException ioe) {
System.out.println("Unexpected exception: " + ioe.getMessage());
} finally {
try {
publishingsocket.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
public void open() throws IOException {
streamIn = new DataInputStream(new BufferedInputStream(
socket.getInputStream()));
}
public void close() throws IOException {
if (socket != null)
socket.close();
if (streamIn != null)
streamIn.close();
}
public static void main(String args[]) {
#SuppressWarnings("unused")
AuServer server = null;
if (args.length != 1)
System.out.println("Usage: java Server port");
else
server = new AuServer(Integer.parseInt(args[0]));
}
}
AppServer.java
import java.net.*;
import java.io.*;
public class AppServer {
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream streamIn = null;
public AppServer(int port) {
try {
System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted: " + socket);
open();
boolean done = false;
while (!done) {
try {
String line = streamIn.readUTF();
System.out.println(line);
done = line.equals("exit");
} catch (IOException ioe) {
done = true;
}
}
close();
} catch (IOException ioe) {
System.out.println(ioe);
}
}
public void open() throws IOException {
streamIn = new DataInputStream(new BufferedInputStream(
socket.getInputStream()));
}
public void close() throws IOException {
if (socket != null)
socket.close();
if (streamIn != null)
streamIn.close();
}
public static void main(String args[]) {
#SuppressWarnings("unused")
AppServer server = null;
server = new AppServer(50090);
}
}
Pls help............
A typically socket server would require some kind of loop where in the server socket would accept incoming connections and spawn a new Thread which would be responsible for actually handling the new Socket connection, leaving the current thread free to continue processing any new incoming connections, for example...
server = new ServerSocket(port);
while (continueAccpetingConnections) {
Socket socket = server.accept();
Thread thread = new Thread(new SocketHandler(socket));
thread.start();
}
The SocketHandler would implement Runnable and provide a constructor that would accept a Socket variable.
It would then be the responsibility of the SocketHandler to actually perform the communications required by the server.
Now, if you wanted to have only one active connection, you might use
while (continueAccpetingConnections) {
Socket socket = server.accept();
process(socket);
}
Which would prevent any new connections until process returned...
Your server is written to accept exactly one connection, process it in the same thread, and then exit. If you want to keep accepting connections, do so, in a loop. If you want to handle clients concurrently, start a new thread to handle each accepted socket.

Categories