Running a Client-Server program written in Java on NetBeans - java

I'm trying to run a client-server program in java on Netbeans.
Here's the code for the server:
// File Name GreetingServer.java
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
int port = Integer.parseInt(args[0]); #line 48, error arises here.
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
Here's the code for the client:
// File Name GreetingClient.java
import java.io.*;
import java.net.*;
public class GreetingClient
{
public static void main(String [] args)
{
String serverName = args[0]; #line 10, error arises here
int port = Integer.parseInt(args[1]);
try
{
System.out.println("Connecting to " + serverName
+ " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out =
new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
So when I want to simulate the client and the server running together I first run the server.
Once the server is running I need to run the client.
However when I try to run the server file, I get the following error:
run:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at GreetingServer.main(GreetingServer.java:48)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Similarly, when I try to run the client program, I get the following error:
run:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at GreetingClient.main(GreetingClient.java:10)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Why is this happening? Please help.
UPDATE:
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private static int port;
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
port=9000;
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
// File Name GreetingClient.java
import java.io.*;
import java.net.*;
public class GreetingClient
{
private static String serverName;
public static void main(String [] args)
{
String sName = "MyServerName";
int port = 9000;
try
{
System.out.println("Connecting to " + sName
+ " on port " + port);
Socket client = new Socket(sName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out =
new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
}
}
}
There is no error on the server side now. But I am still getting the following error on the client side:
run:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at GreetingClient.main(GreetingClient.java:10)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

Your code supposes that you pass the port you want to use as an argument so :
Either you run your application with the line Patryk RoszczyniaƂa posted
If you don't want to use it, just delete the lines :
String serverName = args[0];
int port = Integer.parseInt(args[0]);
and replace them by hardcoded values like :
String serverName = "MyServerName";
int port = 3000;
Update :
I just tested your code, in fact, the serverName is the address you use to connect to the server, so replace it by "localhost" if you are running both client and server on the same machine.
Tested code :
Here is the updated code I tested and it should work perfectly if you run both on the same machine.
Client :
import java.io.*;
import java.net.*;
public class GreetingClient
{
private static String serverName;
public static void main(String [] args)
{
String sName = "localhost";
int port = 9000;
try
{
System.out.println("Connecting to " + sName
+ " on port " + port);
Socket client = new Socket(sName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out =
new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
}
}
}
Server :
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private static int port;
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(20000);
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
port=9000;
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}

To run SocketServer you need to pass port on which server will work. For example:
SocketServer server = new SocketServer(1234);
The problem is that you want to pass port by java argument and you aren't doing that. First of all before use of any variable you should first validate it.
if (args.length>0) {
int port = Integer.parseInt(args[0]); #line 48, error arises here.
}
Your program requires params but I think that you probably run your program without params.
You should run program in this way: java -jar app.jar 1234
But you do it in this way: java -jar app.jar
In this article you will find how to pass parameters to java program using netbeans http://netbeanside61.blogspot.com/2009/02/using-command-line-arguments-in.html.
If you are new in java you should first read this tutorial http://docs.oracle.com/javase/tutorial/networking/sockets/. It's very helpful.

Related

Client and Echo server connected but not client not sending the message to server

A client connects successfully to the server and gets the message "Echo server started.." from the server but when writing to the server nothing happens. Im trying to create an Echo Client program that will connect to the Echo Server (which I assume is successful) now what's left is the communication between the client and the echo server. Any help with to point out the flaw will be appreciated!
Client:
import java.net.*;
import java.util.*;
import java.io.*;
public class GreetinEchoClient {
public static void main(String [] args) throws IOException
{
System.out.println("Echo client ...");
InetAddress localHost = InetAddress.getLocalHost();
Socket socket = new Socket(localHost, 7777);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("We are connected to echo server");
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("Enter message :");
String input = scanner.nextLine();
if("exit".equalsIgnoreCase(input)) {
break;
}
out.println(input);
String response = br.readLine();
System.out.println("Server response :" + response);
} try {
socket.close();
scanner.close();
}catch (IOException e) {}
}
Echo server:
import java.io.*;
import java.net.*;
public class GreetinEcho {
public static void main(String [] args) {
ServerSocket echoServer = null;
String line;
DataInputStream is;
DataOutputStream os;
Socket clientSocket = null;
try {
echoServer = new ServerSocket(7777);
System.out.println("Echo Server Started....");
}
catch (IOException e) {
System.out.println(e);
}
try {
clientSocket = echoServer.accept();
System.out.println("Connected to the client " + clientSocket.getRemoteSocketAddress());
is = new DataInputStream(clientSocket.getInputStream());
os = new DataOutputStream(clientSocket.getOutputStream());
while(true) {
line = is.readUTF();
System.out.println("On Server :" + line);
os.writeUTF(line);
}
} catch (IOException e) {
System.out.println(e);
}
}
}

Java socket programming -- Socket Times out before connection gets complete

I have a socket programming code that goes..
Server Program
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private static int port;
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(50000);
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
port=9000;
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
And the client side code that is...
import java.io.*;
import java.net.*;
public class GreetingClient
{
private static String serverName;
public static void main(String [] args)
{
String sName = "MyServerName";
int port = 9000;
try
{
System.out.println("Connecting to " + sName
+ " on port " + port);
Socket client = new Socket(sName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out =
new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
}
}
}
The code compiles fine. But when i run the program, first the server and then the client, the server displays that
Waiting for client on port 9000...
Socket timed out!
and the client shows
Connecting to MyServerName on port 9000
What is wrong with the code?? I have tried increasing and decreasing the timeout values but it gives the same output.
What is wrong with the code?
There's nothing wrong with your code. You set a 50 second accept timeout, accept blocked for 50 seconds without a client trying to connect, so a SocketTimeoutException was thrown. Everything here is working as designed.
Of course it's possible that:
your accept timeout is too short
you don't want to abort your server just because of an accept timeout
you don't want an accept timeout at all.
All of these are design decisions that depend on your requirements.
It's also possible that you got the host name wrong in the client, but as you're ignoring exceptions in the client:
catch(IOException e)
{
}
there is no way you will ever find out. Never ignore IOExceptions.
Above code is perfectly working with sName in client as 'localhost', since I am running both client and server in my local:
String sName = "localhost";
Verify your server-name if you are expecting client to connect to server.

Creating server in Java for global access

I have a problem which i've already been struggling for 3 days. I need to create server based on socket connection beetween the different local networks.
I found a lot of examples like this :
import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
/**
* Created by yar 09.09.2009
*/
public class HttpServer {
public static void main(String[] args) throws Throwable {
ServerSocket ss = new ServerSocket(9999);
while (true) {
Socket s = ss.accept();
System.err.println("Client accepted");
new Thread(new SocketProcessor(s)).start();
}
}
private static class SocketProcessor implements Runnable {
private Socket s;
private InputStream is;
private OutputStream os;
private SocketProcessor(Socket s) throws Throwable {
this.s = s;
this.is = s.getInputStream();
this.os = s.getOutputStream();
}
public void run() {
try {
readInputHeaders();
writeResponse("<html><body><h1>Hello from Habrahabr</h1></body></html>");
} catch (Throwable t) {
/*do nothing*/
} finally {
try {
s.close();
} catch (Throwable t) {
/*do nothing*/
}
}
System.err.println("Client processing finished");
}
private void writeResponse(String s) throws Throwable {
String response = "HTTP/1.1 200 OK\r\n" +
"Server: YarServer/2009-09-09\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: " + s.length() + "\r\n" +
"Connection: close\r\n\r\n";
String result = response + s;
os.write(result.getBytes());
os.flush();
}
private void readInputHeaders() throws Throwable {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while(true) {
String s = br.readLine();
if(s == null || s.trim().length() == 0) {
break;
}
}
}
}
}
But problem is :
i can access to this ip:port only from the same local network. If i trying to connect from the same network (from Android smartphone to local computer which has the same network ip)? so in this case all is successful, but if i trying to run the same Server sample code on, say for example AWS (Amazon Web Server)
it doesn't work :(
-> Couldn't get I/O for the connection to 172.31.23.98 (java)
or
-> org.apache.http.conn.ConnectTimeoutException: Connect to 172.31.23.98:9999 timed out (groovy)
i'm using this sample code of Server :
public static void main(String[] args) throws IOException {
int portNumber = 9998;
BufferedOutputStream bos = null;
while (true) {
try (ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
InputStream in = clientSocket.getInputStream();
BufferedReader inWrapper = new BufferedReader(new InputStreamReader(in))) {
FileOutputStream fos = new FileOutputStream(new File("D:/BufferedAudio.wav"));
bos = new BufferedOutputStream(fos);
System.out.println("Connected with client");
String inputLine, outputLine;
int bytesRead;
byte[] buffer = new byte[1024 * 1024];
while ((bytesRead = in.read(buffer)) > 0) {
bos.write(buffer, 0, bytesRead);
System.out.println(new String(buffer, Charset.defaultCharset()));
bos.flush();
out.println("Hello!!! I'm server");
}
bos.close();
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
throw e;
}
System.out.println("Upps, the loop was unexpectedly out");
}
}
Here's the code of client :
public static void main(String[] args) throws IOException {
String IP = "172.31.23.98";
int port = 9998;
try (
Socket connectionSocket = new Socket(IP, port);
PrintWriter out = new PrintWriter(connectionSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()))
) {
BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + IP);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
IP);
System.exit(1);
}
}
These are the samples from the internet.
Amm how can i modify this code to access from Client to Server from different networks ?
The IP range 172.16.0.0 to 172.31.255.255 is a private address space for use in local area networks. IPs from that range are only valid in the same private LAN.
When you deploy your server software on a host on the Internet which is outside of your local area network, you need to replace it with the IP address of that host. I never used AWS, but the first place I would be looking for when I would want to know the public IP address of a server I rent, would be the web-based control panel. When you have shell access to the server, you can also find it out with ipconfig on Windows and ifconfig on Unix.

Client Not Connecting to Server

So I have my server that looks like this
import java.net.*;
import java.io.*;
public class Server extends Thread {
private ServerSocket serverSocket;
public Server(int port) throws IOException {
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(20000);
}
public void run() {
while(true) {
try {
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args) {
int port = 5000;
try {
Thread t = new Server(port);
t.start();
}catch(IOException e) {
e.printStackTrace();
}
}
}
And when I run it, everything goes fine. I also have my client which looks like this.
import java.net.*;
import java.io.*;
public class Client {
public static void main(String [] args) {
String serverName = "Server";
int port = 5000;
try {
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e) {
System.out.println("Error!");
}
}
}
After running my client I get this in the console.
Connecting to Server on port 5000
java.net.UnknownHostException: Server
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at maple.Client.main(Client.java:16)
Line 16 looks like this
Socket client = new Socket(serverName, port);
EDIT:
After changing to a valid server address when I run the code I only get certain statements to run and then it just times out. Why is this?
Waiting for client on port 5000...
Just connected to /127.0.0.1:57355
Hello from /127.0.0.1:57355
Waiting for client on port 5000...
Socket timed out!
The server name is assigned to the String literal "Server" rather than a valid host address.
Its timing out because in constructor you are setting a 20 sec time to live.
serverSocket.setSoTimeout(20000);
Remove this and you should be fine.

Java server , client program

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.

Categories