Getting error in client-server programming - java

I have created client Server program in java. While I run program I should get port number and IP address but I am getting an error while I run Client.java. Below is my both files.
Server.java
package serverpro;
import java.io.*;
import static java.lang.ProcessBuilder.Redirect.to;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Server extends Thread {
public static final int PORT_NUMBER = 12345;
protected Socket socket;
public static void main(String[] args) {
ServerSocket server = null;
try {
server = new ServerSocket(PORT_NUMBER);
while (true) {
new Server(server.accept());
}
}
catch(IOException ex) {
System.out.println("Unable to start server or acccept connections ");
System.exit(1);
}
finally {
try {
server.close();
}
catch(IOException ex) {
// not much can be done: log the error
// exits since this is the end of main
}
}
}
private Server(Socket socket) {
this.socket = socket;
start();
}
// the server services client requests in the run method
public void run() {
InputStream in = null;
OutputStream out = null;
BufferedReader inReader = new BufferedReader(newInputStreamReader(in));
// the constructor argument “true” enables auto-flushing
PrintWriter outWriter = new PrintWriter(out, true);
outWriter.println("Echo server: enter bye to exit.");
//outWriter.println(“Echo server: enter ‘bye’ to exit.”);
while (true) {
// readLine blocks until a line-terminated string is available
String inLine;
try {
inLine = inReader.readLine();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
// readLine returns null if the client just presses <return>
try {
in = socket.getInputStream();
out = socket.getOutputStream();
// ... do useful stuff ...
}
catch(IOException ex) {
System.out.println("Unable to get Stream from ");
}
finally {
try {
in.close();
out.close();
socket.close();
}
catch(IOException ex) {
// not much can be done: log the error
}
}
}
}
}
Client.java
package serverpro;
import java.io.*;
import java.net.*;
public class Client {
public static void main(String args[]) throws IOException {
new Client(args[0]);
}
public Client(String host) throws IOException {
Socket socket;
try {
socket = new Socket(host, Server.PORT_NUMBER);
}
catch(UnknownHostException ex) {
System.out.println(host + " is not a valid host name.");
return;
}
catch(IOException ex) {
System.out.println("Error connecting with" + host);
return;
}
// … initialize model, GUI, etc. ...
InputStream in = null;
OutputStream out = null;
try {
in = socket.getInputStream();
out = socket.getOutputStream();
// ... do useful stuff ...
}
finally {
try {
in.close();
out.close();
socket.close();
}
catch(IOException ex) {
// not much can be done ...
}
}
}
}
Here is the error code I am getting while running client.java file
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at serverpro.Client.main(Client.java:13)
/Users/Puja Dudhat/Library/Caches/NetBeans/8.2/executor- snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)

Your code expects one argument passed into the main method, which appears to be your client port, stored at args[0]. Therefore, you have to provide one to the main method. An example for setting port=12345:
java Server 12345
If you'd need more arguments, (e.g. a value at args[1]), then simply add another argument when launching main:
java Server 12345 secondArg

Assuming you are not passing required command-line argument. When I ran this code it did run fine, provided the argument required is passed or hard-coded; namely:
public static void main(**String args[]**) throws IOException {
new Client(**args[0]**);
}

if you are running both server and client on same machine then you can pass localhost as command line argument
java Client localhost
Alternatively, you can hard code host value(note : this is not good practice though),
public static void main(String args[]) throws IOException {
new Client("localhost");
}
Also as a suggestion, you can use ide like eclipse or intellij to debug your code step by step. you can go through online video tutorials for java and many are available on youtube

Related

How to listen to port 80 by using Java Socket

I have a server whose port 80 is for occupied by HTTP transactions. I wanted to see the traffic in that port and I tried to use a socket program to listen to that port.
public Server(int serverPort) throws IOException {
super(serverPort);
try {
while (true) {
Socket socket = accept();
new ServerThread(socket);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
close();
}
}
// inner-class ServerThread
class ServerThread extends Thread {
private Socket socket;
private BufferedReader in;
private PrintWriter out;
// Ready to conversation
public ServerThread(Socket s) throws IOException {
this.socket = s;
in = new BufferedReader(new InputStreamReader(socket
.getInputStream(), "UTF-8"));
out = new PrintWriter(socket.getOutputStream(), true);
start();
}
// Execute conversation
public void run() {
try {
// Communicate with client until "bye " received.
while (true) {
String line = in.readLine();
if (line == null || "".equals(line.trim())) {
break;
}
System.out.println("Received message: " + line);
out.println(line);
out.flush();
}
out.close();
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
new Server(80);
}
However, when I run that java application, it showed a BindException: Address already in use.
So what should I do to my code and make it listen to port 80, or are there any other ways to listen to that port in Java?
If I understand you correctly you are trying to sniff the packets that are being passed to your server. If that is the case there are some answers in this post.
What Server are you running it on?
it all depends on the type of server you're working on. Tomcat for example has the type of port it's running off of in the Server.xml file.
In Windows you can run your program by administrator. In Linux using root user.

Single client to multiple client support: multithreading conversion in java

So I don't know who to go about creating a multithreaded server. I have client and server working fine together but can't introduce multiple clients properly. Here is my Server code:
package dod;
import java.net.*;
import java.io.*;
import dod.game.GameLogic;
public class Server{
Server(GameLogic game, int port) throws IOException{
ServerSocket ss = null;
Socket sock = null;
try{
ss = new ServerSocket(4444);//port no.
while(true){
try{
sock = ss.accept();
ClientThread thread = new ClientThread(game, sock);
System.out.println("Adding new player...");
thread.run();
}catch(final Exception e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
}catch(Exception d){
System.out.println(d);
}finally{
if(ss!=null){
ss.close();
}
}
}
}
Here is my thread class:
package dod;
import java.io.*;
import java.net.Socket;
import dod.game.GameLogic;
import dod.game.PlayerListener;
public class ClientThread extends CommandLineUser implements PlayerListener, Runnable{
DataInputStream in;
PrintStream out;
// The game which the command line user will operate on.
// This is private to enforce the use of "processCommand".
ClientThread(GameLogic game, Socket sock) {
super(game);
try{
in = new DataInputStream(sock.getInputStream());
out = new PrintStream(sock.getOutputStream());
}catch(IOException ioe){
System.out.println(ioe);
}
game.addPlayer(this);
}
/**
* Constantly asks the user for new commands
*/
public void run() {
System.out.println("Added new human player.");
// Keep listening forever
while(true){
try{
// Try to grab a command from the command line
final String command = in.readLine();;
// Test for EOF (ctrl-D)
if(command == null){
System.exit(0);
}
processCommand(command);
}catch(final RuntimeException e){
System.err.println(e.toString());
System.exit(1);
} catch (final IOException e) {
System.err.println(e.toString());
System.exit(1);
}
}
}
/**
* Outputs a message to the player
*
* #param message
* the message to send to the player.
*/
public void outputMessage(String message) {
out.print(message);
}
}
Not asking for new code as such, just need pointers as to what I need to do have multiple client connection at the same time! Thanks to anyone who helps out!
To start, add new Thread(clientThread) in the server and call start() on it - as is everything's happening on the same thread.
public class Server{
Server(GameLogic game, int port) throws IOException{
ServerSocket ss = null;
Socket sock = null;
try{
ss = new ServerSocket(4444);//port no.
while(true){
try{
sock = ss.accept();
ClientThread thread = new ClientThread(game, sock);
System.out.println("Adding new player...");
thread.start(); //you have to use start instead of run method to create multi thread application.
}catch(final Exception e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
}catch(Exception d){
System.out.println(d);
}finally{
if(ss!=null){
ss.close();
}
}
}
}
You have to use start instead of run method to create multi thread application.
If you want to send messages about new connections you have to hold sock in a list and when a new connection accepted send message to all socket object in list. (server broadcasts to all connected sockets)
I hope it helps.

Simple Socket program

Hey guys I'm trying to write a simple socket program that basically send like a "Hello" message from client and then server gets and print its out.
I'm trying to follow this guide: http://www.javaworld.com/jw-12-1996/jw-12-sockets.html?page=4
However when i try to instantiate serverSocket with port number it causes syntax error that advises to either remove the argument or create a new constructor for that method. It also doesn't recognize accept() method when I try to use it. Anyone know why this is happening?
Here is my Client code:
public static void main(String[] args) throws UnknownHostException, IOException
{
Socket testSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
try
{
testSocket = new Socket("192.168.0.104", 5932);
os = new DataOutputStream(testSocket.getOutputStream());
is = new DataInputStream(testSocket.getInputStream());
}
catch (UnknownHostException e)
{
System.err.println("Couldn't find Host");
}
catch (IOException e)
{
System.err.println("Couldn't get I/O connection");
}
if (testSocket != null && os != null && is != null)
{
try
{
os.writeBytes("Hello Server!\n");
os.close();
is.close();
testSocket.close();
}
catch (UnknownHostException e)
{
System.err.println("Host not found");
}
catch (IOException e)
{
System.err.println("I/O Error");
}
}
}
Here is my Server Code (UPDATED):
public static void main(String[] args)
{
String line = new String() ;
try
{
ServerSocket echoServer = new ServerSocket(5932);
Socket clientSocket = echoServer.accept();
DataInputStream is = new DataInputStream(clientSocket.getInputStream());
PrintStream os = new PrintStream(clientSocket.getOutputStream());
while (true) {
line = is.readLine();
os.println(line);
}
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
Here are actual screenshots.
Error1: http://i.imgur.com/8JIOd.png
Error2: http://i.imgur.com/7uCow.png
Your class is named ServerSocket. It doesn't have a constructor that takes an int. Name your class something else so it doesn't conflict with java.net.ServerSocket.
Either that use the absolute path
java.net.ServerSocket clientSocket = new java.net.ServerSocket(5932)
You have not posted import statements. Classes ServerSocket, Socket etc belong to package java.net. Double check that you have import statements in the beginning of your class.
something like import java.net*. Or, better use IDE to help you. Ctrl-Shift-O in Eclipse will do the work.
Try it this way....
- First check that you have properly imported the package java.net.*
public static void main(String[] args)
{
String line = new String() ;
try
{
ServerSocket echoServer = new ServerSocket(5932);
Socket clientSocket = echoServer.accept();
DataInputStream is = new DataInputStream(clientSocket.getInputStream());
PrintStream os = new PrintStream(clientSocket.getOutputStream());
while (true) {
line = is.readLine();
os.println(line);
}
}
catch (IOException e)
{
System.out
}
}
EDIT BASED ON SCREEN SHOTS:
The class you defined is named ServerSocket. This is hiding the actual class you are trying to use. Your class does not implement a constructor that takes an int and does not define accept(), these are the errors you are receiving. You should not name your class the same name as another existing class as it leads to these types of errors and further confusion.
ORIGINAL:
You have an syntax error when you handle the exception thrown by the ServerSocket.
try
{
echoServer = new ServerSocket(5932);
}
catch (IOException e)
{
System.out
}
It looks like you are missing .println(e); from the end of the last line.

Infinite loop when deploying OSGI bundle with network server

I'm trying to implement OSGI bundle with network server which uses network sockets.
This is the complete source code: http://www.2shared.com/file/RMXby331/CB_27.html
This is the Activator:
package org.DX_57.osgi.CB_27.impl;
import java.util.Properties;
import org.DX_57.osgi.CB_27.api.CBridge;
import org.DX_57.osgi.CB_27.impl.EchoServer;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
public class CBridgeApp implements BundleActivator {
public void start(BundleContext bc) throws Exception {
ServiceRegistration registerService = bc.registerService(CBridge.class.getName(), new CBridgeImpl(), new Properties());
EchoServer();
}
public void stop(BundleContext bc) throws Exception {
boolean ungetService = bc.ungetService(bc.getServiceReference(CBridge.class.getName()));
}
private void EchoServer() {
EchoServer method = new EchoServer();
}
}
This is the source code if the Java Network server:
package org.DX_57.osgi.CB_27.impl;
import java.net.*;
import java.io.*;
public class EchoServer
{
ServerSocket m_ServerSocket;
public EchoServer()
{
try
{
// Create the server socket.
m_ServerSocket = new ServerSocket(12111);
}
catch(IOException ioe)
{
System.out.println("Could not create server socket at 12111. Quitting.");
System.exit(-1);
}
System.out.println("Listening for clients on 12111...");
// Successfully created Server Socket. Now wait for connections.
int id = 0;
while(true)
{
try
{
// Accept incoming connections.
Socket clientSocket = m_ServerSocket.accept();
// accept() will block until a client connects to the server.
// If execution reaches this point, then it means that a client
// socket has been accepted.
// For each client, we will start a service thread to
// service the client requests. This is to demonstrate a
// multithreaded server, although not required for such a
// trivial application. Starting a thread also lets our
// EchoServer accept multiple connections simultaneously.
// Start a service thread
ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++);
cliThread.start();
}
catch(IOException ioe)
{
System.out.println("Exception encountered on accept. Ignoring. Stack Trace :");
ioe.printStackTrace();
}
}
}
public static void main (String[] args)
{
new EchoServer();
}
class ClientServiceThread extends Thread
{
Socket m_clientSocket;
int m_clientID = -1;
boolean m_bRunThread = true;
ClientServiceThread(Socket s, int clientID)
{
m_clientSocket = s;
m_clientID = clientID;
}
public void run()
{
// Obtain the input stream and the output stream for the socket
// A good practice is to encapsulate them with a BufferedReader
// and a PrintWriter as shown below.
BufferedReader in = null;
PrintWriter out = null;
// Print out details of this connection
System.out.println("Accepted Client : ID - " + m_clientID + " : Address - " +
m_clientSocket.getInetAddress().getHostName());
try
{
in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream()));
// At this point, we can read for input and reply with appropriate output.
// Run in a loop until m_bRunThread is set to false
while(m_bRunThread)
{
// read incoming stream
String clientCommand = in.readLine();
System.out.println("Client Says :" + clientCommand);
if(clientCommand.equalsIgnoreCase("quit"))
{
// Special command. Quit this thread
m_bRunThread = false;
System.out.print("Stopping client thread for client : " + m_clientID);
}
else
{
// Echo it back to the client.
out.println(clientCommand);
out.flush();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
// Clean up
try
{
in.close();
out.close();
m_clientSocket.close();
System.out.println("...Stopped");
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
}
When I try to deploy the bundle on Glassfish server the application server hangs but I can connect to the java network server using the java client. It seems that there is a infinite loop. I need help to fix the code.
Best wishes
Your bundle activator start method never returns, because you're calling constructor of your service with infinite loop. A good practice is to return as fast as possible from bundle activators.
Here is an idea how to rewrite your code:
public class EchoServer {
private volatile boolean started;
public void start() {
new Thread(new Runnable() {
#Override
public void run() {
started = true;
try {
m_ServerSocket = new ServerSocket(12111);
} catch(IOException ioe) {
System.out.println("Could not create server socket at 12111. Quitting.");
System.exit(-1);
}
System.out.println("Listening for clients on 12111...");
// Successfully created Server Socket. Now wait for connections.
int id = 0;
while (started) {
try {
Socket clientSocket = m_ServerSocket.accept();
ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++);
cliThread.start();
} catch(IOException ioe) {
System.out.println("Exception encountered on accept. Ignoring. Stack Trace :");
ioe.printStackTrace();
}
}
}
}).start();
}
public void stop() {
started = false;
}
}
Activator
public class CBridgeApp implements BundleActivator {
private EchoServer method;
public void start(BundleContext bc) throws Exception {
...
method = new EchoServer();
method.start();
}
public void stop(BundleContext bc) throws Exception {
...
method.stop();
}
}

Java - running multiple clients with eclipse

I've got codes of a server and clients written on Java. But the question is how to run multiple clients on DIFFERENT console-windows with Eclipse when server is running? Thx for helping!
(solved!!)
UPDATE**
Another question: I'll create a new question
Server:
import java.net.*;
import java.io.*;
public class ATMServer {
private static int connectionPort = 8989;
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
try {
serverSocket = new ServerSocket(connectionPort);
} catch (IOException e) {
System.err.println("Could not listen on port: " + connectionPort);
System.exit(1);
}
System.out.println("Bank started listening on port: " + connectionPort);
while (listening)
new ATMServerThread(serverSocket.accept()).start();
serverSocket.close();
}
}
ServerThread:
import java.io.*;
import java.net.*;
public class ATMServerThread extends Thread {
private Socket socket = null;
private BufferedReader in;
PrintWriter out;
public ATMServerThread(Socket socket) {
super("ATMServerThread");
this.socket = socket;
}
public void run(){
}
}
}
Client: (**UPDATE)
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ATMClient {
private static int connectionPort = 8989;
public static void main(String[] args) throws IOException {
Socket ATMSocket = null;
PrintWriter out = null;
BufferedReader in = null;
String adress = "";
try {
adress = "127.0.0.1";
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Missing argument ip-adress");
System.exit(1);
}
try {
ATMSocket = new Socket(adress, connectionPort);
out = new PrintWriter(ATMSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader
(ATMSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Unknown host: " +adress);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't open connection to " + adress);
System.exit(1);
}
out.close();
in.close();
ATMSocket.close();
}
You can run as many socket clients from Eclipse provided that you pass user-defined ip/port info as command arguments from main() under Program Arguments tab in Run Configuration dialog for that program inside Eclipse rather than using some hardwired values for ip/port.
To create multiple console views (via separate Console View tabs rather than clicking on each instance), you need to create a new console view for each target instance in Eclipse Debug View mode; to achieve this, you need to select "New Console View" (from the icon button with the plus symbol to the far right of the Console View) and assign which program instance to view from each new console.
Another question: if I have to change something on ServerThread, for example, add a title, is that possible to execute that without restart the server?
Which title? I don't see any GUI code for the ServerThread code snippet. Do you mean the title name of the Console view tab?

Categories