Why am I getting a NoSuchElementException in this Java client/server setup? - java

I am making a java client/server socket program in netbeans that is supposed to accept a number and then return the square root/square the number.
It allows me to type in a number and then i get the following statement:
Exception found in Client: java.util.NoSuchElementException.
I am not sure why it is doing this, please help!
Here is my code for both classes:
Client:
package question1.clientserver;
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
try {
int number, temp;
Scanner sc = new Scanner(System.in);
Socket s = new Socket("127.0.0.1", 1452);
Scanner sc1 = new Scanner(s.getInputStream());
System.out.println("Enter any number to be squared");
number = sc.nextInt();
PrintStream p = new PrintStream(s.getOutputStream());
p.println(number);
temp = sc1.nextInt();
System.out.println(temp);
} catch (Exception e) {
System.out.println("Exception found in Client: " + e);
}
}
}
and this is my server code
package question1.clientserver;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static void main(String[] args) {
while (true) {
System.out.println("Waiting for connection, please stand by...");
try {
int number, temp;
ServerSocket s1 = new ServerSocket(1452);
Socket ss = s1.accept();
System.out.println("Connection has been established");
Scanner sc = new Scanner(ss.getInputStream());
number = sc.nextInt();
temp = number * number;
PrintStream p = new PrintStream(ss.getOutputStream());
p.println(temp);
} catch (Exception e) {
System.out.println("Exception in Server while creating connection" + e);
}
}
}
}
}
if you have any ideas or suggestions please let me know!
stacktrace
run: Enter any number to be squared
25 (which is what i type in for example)
Exception found in Client: java.util.NoSuchElementException
Build Successful (total time: 31 seconds)

Related

Need help on Pi Calculation with single multiServer - (N)Clients programm on Java. (Sockets)

I am trying to make a single mutlithreaded Server , that many clients can connect. Every client takes his iD and a number of steps and tries to calculate Pi =3,14 with accuracy, after that every client sends its result back to Server and the Server Calculates the Final result finnaly prints Pi.
(Every Client works at the same time).
(We know from start how many Clients will connect)
So far I created the main Server , the ServerThread , and a ServerProtocol where every action is written there. A loop helps that many clients can connect. I gave as a string the specific number of client and the numSteps it has to calculate pi.
On the client side, I made the main Client and the ClientProtocol with the actions. So , the client take the string, make it integer and start calculating pi. At the end sends the result as a string and the Server makes it Integer and put it on an Array to calculate and print 3.14 .
So i am somewhere lost and can't find where , so any help will be aprecciated.
Server
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ServerTCP {
private static final int PORT = 1234;
public static String num;
public static Lock lock = new ReentrantLock();
public static int clientsSoFar=-1;
public static void main(String[] args) throws IOException {
// server is listening on port
ServerSocket connectionSocket = new ServerSocket(PORT);
System.out.println("Server is listening to port: " + PORT);
// running infinite loop for getting client request
while(true) {
//Wait for connection and produce actual socket
Socket dataSocket = null;
// socket object to receive incoming client requests
dataSocket=connectionSocket.accept();
clientsSoFar++;
System.out.println("Received request from " + dataSocket.getInetAddress());
//Server Thread
ServerTCPThread sthread = new ServerTCPThread(dataSocket);
sthread.start();
}
}
}
ServerThread
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Arrays;
public class ServerTCPThread extends Thread{
public static int clientsSoFar;
private Socket dataSocket;
private InputStream is;
private BufferedReader in;
private OutputStream os;
private PrintWriter out;
private static final String EXIT = "!";
public ServerTCPThread(Socket socket)
{
dataSocket = socket;
try {
is = dataSocket.getInputStream();
in = new BufferedReader(new InputStreamReader(is));
os = dataSocket.getOutputStream();
out = new PrintWriter(os,true);
}
catch(IOException e) {
System.out.println("I/O Error " + e);
}
}
public void run() {
int clientsP =2;
int numSteps=100;
String p = "2 100";
String inmsg, outmsg;
try {
//epeksergasia
String num1 = String.valueOf(ServerTCP.clientsSoFar);
String num2 = String.valueOf(numSteps/clientsP);
ServerTCP.num =num1+" "+num2;
//epeksergasia
int numClient;
String[] splited = p.split("\\s+");
numClient=Integer.parseInt(splited[0]);
ServerTcpProtocol app = new ServerTcpProtocol();
outmsg = app.message();
out.println(outmsg);
inmsg = in.readLine();
outmsg = app.processRequest(inmsg);
// while(!EXIT.equals(inmsg)) {
// outmsg = app.processRequest(inmsg);
//out.println(outmsg);
//inmsg = in.readLine();
// }
double outMsgDouble = Double.parseDouble(outmsg);
double [] pin = new double[clientsP];
Arrays.fill(pin, 0);
ServerTCP.lock.lock();
for (int i=0; i<clientsP; i++)
if (pin[i]==0)
pin[i]=outMsgDouble;
ServerTCP.lock.unlock();
dataSocket.close();
}
catch (IOException e) {
System.out.println("I/O Error --> " + e);
}
}
}
ServerProtocol
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ServerTcpProtocol {
public String processRequest(String theInput) {
System.out.println("Received message from client: " + theInput);
String theOutput = theInput;
//System.out.println("Send message to client: " + theOutput);
return theOutput;
}
BufferedReader user = new BufferedReader(new InputStreamReader(System.in));
public String message() throws IOException {
System.out.println("Send number to Client: "+ ServerTCP.num);
//String theOutput = user.readLine();
String theOutput=ServerTCP.num;
//SimpleServerTCP.p="+1";
return theOutput;
}
}
Client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ClientTCP {
//Client should know servers address/name
private static final String HOST = "localhost";
private static final int PORT = 1234;
private static final String EXIT = "!";
public static double sum;
public static Lock lock = new ReentrantLock();
public static void main(String[] args) throws IOException {
//Try to connect to server
Socket dataSocket = new Socket(HOST, PORT);
//Set up input and output streams
InputStream is = dataSocket.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
OutputStream os = dataSocket.getOutputStream();
PrintWriter out = new PrintWriter(os, true);
System.out.println("Connection to " + HOST + " established.");
//Send request and then receive and process reply
String inmsg, outmsg;
ClientTcpProtocol app = new ClientTcpProtocol();
inmsg = in.readLine();
System.out.println("Time to send back to Server");
outmsg = app.answere(inmsg);
out.println(outmsg);
//Socket close
dataSocket.close();
System.out.println("Data Socket closed.");
}
}
ClientProtocol
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ClientTcpProtocol {
BufferedReader user = new BufferedReader(new InputStreamReader(System.in));
//Request comes from user input
public String prepareRequest() throws IOException {
System.out.print("Enter message to send to server:");
String theOutput = user.readLine();
return theOutput;
}
//Reply goes to user screen
public void processReply(String theInput) throws IOException {
System.out.println("Message received from server: " + theInput);
}
public String answere(String theInput) {
System.out.println("Received message from Server: " + theInput);
//String theOutput = theInput;
int myId;
double result=0;
int myStart=1;
int myStop;
int numStep;
double table= 0;
int numStep0;
int numStep1;
int numStep2;
int numStep3;
int numStep4;
//Input split
String[] splited = theInput.split("\\s+");
myId = Integer.parseInt(splited[0]);
numStep=Integer.parseInt(splited[1]);
myStop=numStep;
double step = 1.0 / (double)numStep;
ClientTCP.lock.lock();
try {
for(int i = myStart; i < myStop; i++) {
double x = ((double)i+0.5)*step;
table += 4.0/(1.0+x*x);
}
//Maybe this oart should be at the end of Server before calculation???
result = result + ( table * step);
String theOutput = Double.toString(result);
System.out.println("Send p to Server:" + theOutput);
return theOutput;
}finally {
ClientTCP.lock.unlock();
}
}
}

Java Client-Server Programming: Shared Memory Between Clients

I am developing a simple 2D multiplayer game in Java, following the Client-Server model. The functionality in terms of the socket programming is simple:
A Client sends the Server their character data (x position, y position, health points, etc.)
The Server registers the updated character data in a table which is storing all the different Clients' character data
The Server sends back the table to the Client so that they can render the other characters
I am running into a weird issue that I would like help understanding so I can move forward with the project. Here is the code I'm running right now.
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Set;
import java.util.Vector;
import java.util.HashSet;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server
{
private static Vector<Integer> IDs = new Vector<>();
public static void main(String[] args) throws Exception
{
ExecutorService pool = Executors.newFixedThreadPool(32);
try (ServerSocket listener = new ServerSocket(40000))
{
System.out.println("The server is up.");
while (true)
{
pool.execute(new Player(listener.accept()));
}
}
}
private static class Player implements Runnable
{
private Socket socket;
private Scanner input;
private PrintWriter output;
private int ID;
public Player(Socket socket)
{
this.socket = socket;
this.ID = IDs.size() + 1;
IDs.add(ID);
}
public void run()
{
try
{
input = new Scanner(socket.getInputStream());
output = new PrintWriter(socket.getOutputStream(), true);
while(input.hasNextLine())
{
String result = "";
for(int i = 0; i < IDs.size(); i++)
{
result += (IDs.get(i) + " ");
}
output.println(result);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws Exception {
try (Socket socket = new Socket("127.0.0.1", 40000)) {
Scanner scanner = new Scanner(System.in);
Scanner in = new Scanner(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while (scanner.hasNextLine()) {
out.println(scanner.nextLine());
System.out.println(in.nextLine());
}
in.close();
scanner.close();
}
}
}
What I want to happen is: every time a Client sends any message to the Server, the Server responds with a list of IDs (each Client that connects gets a fresh ID).
What is actually happening:
The second Client that connects is able to see that there is a first Client that is already connected. But the first Client is not able to see that there is a second Client connected.
Thank you for your help.
The server loop
while(input.hasNextLine())
{
String result = "";
for(int i = 0; i < IDs.size(); i++)
{
result += (IDs.get(i) + " ");
}
output.println(result);
}
never calls input.nextLine(), which means that input.hasNextLine() is always true, so the server floods the socket with output until the buffer is full.
This can be seen by starting a client, killing the server, then keep pressing enter. The client keeps receiving data, even though the server is gone, until the buffer is emptied.
Add the following line inside the loop:
System.out.println(this.ID + ": " + input.nextLine());
This will make the server consume the line from the client, as was intended, and allow you to see / verify the data flowing.

objectInputStream.readObject() throws exception java.io.OptionalDataException

Can someone please resolve this issue.
Using JDK 1.8, I am trying to build a very simple chat application in Java using Sockets. In my client class as soon as following line executes
Message returnMessage = (Message) objectInputStream.readObject();
it throws exception.
Exception in thread "main" java.io.OptionalDataException
I am writing only objects of type Message to the stream and reading objects of type Message, since i wrote once, i dont think i am doing anything wrong in reading them in sequence.
Q. Also please let me know what is the best way to debug this type of application, how to hit the breakpoint in server while running client ?
Client
package com.company;
import sun.misc.SharedSecrets;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException{
Socket socket = new Socket("localhost", Server.PORT);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String readerInput = bufferedReader.readLine();
String[] readerInputTokens = readerInput.split("\u0020");
if(readerInputTokens.length != 2) {
System.out.println("Usage: Client <integer> <integer>");
} else {
Integer firstNumber = Integer.decode(readerInputTokens[0]);
Integer secondNumber = Integer.decode(readerInputTokens[1]);
Message message = new Message(firstNumber, secondNumber);
objectOutputStream.writeObject(message);
System.out.println("Reading Object .... ");
Message returnMessage = (Message) objectInputStream.readObject();
System.out.println(returnMessage.getResult());
socket.close();
}
}
public static boolean isInteger(String value) {
boolean returnValue = true;
try{Integer.parseInt(value);}
catch (Exception ex){ returnValue = false; }
return returnValue;
}
}
Server
package com.company;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public final static int PORT = 4446;
public static void main(String[] args) throws IOException, ClassNotFoundException {
new Server().runServer();
}
public void runServer() throws IOException, ClassNotFoundException {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server up & ready for connections ...");
// This while loop is necessary to make this server able to continuously in listning mode
// So that whenever a client tries to connect, it let it connect.
while (true){
Socket socket = serverSocket.accept(); // Server is ready to accept connectiosn;.
// Initialize Server Thread.
new ServerThread(socket).start();
}
}
}
Sever Thread
package com.company;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class ServerThread extends Thread {
private Socket socket = null;
ServerThread(Socket socket){
this.socket = socket;
}
public void run() {
try {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
objectOutputStream.writeChars("\n");
objectOutputStream.flush();
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
Message message = (Message) objectInputStream.readObject();
multiplyNumbers(message);
System.out.println("Writing: "+message.toString());
objectOutputStream.writeObject(message);
System.out.println("Message Written");
socket.close();
} catch( IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
private void multiplyNumbers(Message message) {
message.setResult(message.getFirstNumber().intValue() * message.getSecondNumber().intValue());
}
}
Message Class
package com.company;
import java.io.Serializable;
public class Message implements Serializable {
private static final long serialVersionUID = -72233630512719664L;
Integer firstNumber = null;
Integer secondNumber = null;
Integer result = null;
public Message(Integer firstNumber, Integer secondNumber) {
this.firstNumber = firstNumber;
this.secondNumber = secondNumber;
}
public Integer getFirstNumber() {
return this.firstNumber;
}
public Integer getSecondNumber() {
return this.secondNumber;
}
public Integer getResult() {
return this.result;
}
public void setResult(Integer result) {
this.result = result;
}
#Override
public String toString() {
return "Message{" +
"firstNumber=" + firstNumber +
", secondNumber=" + secondNumber +
", result=" + result +
'}';
}
}
objectOutputStream.writeChars("\n");
Why are you writing a newline to an ObjectOutputStream? You're never reading it. Don't do that. Remove this wherever encountered.

java port scanner not working

I am taking a free online course for cybersecurity here https://cybersecuritybase.github.io/
Par of the course they want you to create a java port scanner they provide some of the code and you add the port scanner portion and i am having issues with it. Java is not a language i am really familiar with so i feel it's something simple but can't seem to figure it out.
code is here
package sec.portscanner;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.InetSocketAddress;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
import java.io.IOException;
public class PortScanner {
final static int MIN_PORT = 1024;
final static int MAX_PORT = 49151;
public static void main(String[] args) throws Exception {
Scanner reader = new Scanner(System.in);
System.out.println("Which address should I scan?");
String address = reader.nextLine();
System.out.println("Start at port?");
int start = Integer.parseInt(reader.nextLine());
System.out.println("End at port?");
int end = Integer.parseInt(reader.nextLine());
Set<Integer> ports = getAccessiblePorts(address, start, end);
System.out.println("");
if (ports.isEmpty()) {
System.out.println("None found :(");
} else {
System.out.println("Found:");
ports.stream().forEach(p -> System.out.println("\t" + p));
}
}
public static Set<Integer> getAccessiblePorts(String address, int start, int end) {
Set<Integer> accessiblePorts = new TreeSet<>();
start = Math.max(start, MIN_PORT);
end = Math.min(end, MAX_PORT);
for (int port = start; port <= end; port++)
{
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(address, port), 50000);
socket.close();
} catch(IOException e) {
System.out.println(e);
}
}
return accessiblePorts;
}
}
The portion I created is the for loop with the socket scan. It always prints out none found no matter what address i provide and i am not sure how to fix this. any pointers would be great I have searched and from what i see nothing is stand out wrong( at least i hope)
you are not adding to the accessiblePorts Set
try
Socket socket = new Socket();
socket.connect(new InetSocketAddress(address, port), 50000);
socket.close();
accessiblePorts.add (port);

Connect multiple clients to one server

I'm trying to connect all my clients to one server. I've done some research and found out that the easiest way to do it is create a new thread for every client that connects to the server. But I am already stuck on the part where a client disconnects and reconnect.
Client
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Test {
private static int port = 40021;
private static String ip = "localhost";
public static void main(String[] args) throws UnknownHostException,
IOException {
String command, temp;
Scanner scanner = new Scanner(System.in);
Socket s = new Socket(ip, port);
while (true) {
Scanner scanneri = new Scanner(s.getInputStream());
System.out.println("Enter any command");
command = scanner.nextLine();
PrintStream p = new PrintStream(s.getOutputStream());
p.println(command);
temp = scanneri.nextLine();
System.out.println(temp);
}
}
}
Server
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class MainClass {
public static void main(String args[]) throws IOException {
String command, temp;
ServerSocket s1 = new ServerSocket(40021);
while (true) {
Socket ss = s1.accept();
Scanner sc = new Scanner(ss.getInputStream());
while (sc.hasNextLine()) {
command = sc.nextLine();
temp = command + " this is what you said.";
PrintStream p = new PrintStream(ss.getOutputStream());
p.println(temp);
}
}
}
}
When I connect once it works correctly but as soon as I disconnect the client and try to reconnect (or connect a second client) it does not give an error or anything it just does not function. I am trying to keep it as basic as possible.
The output with one client:
When I try and connect a second client:
I hope someone could help me out. Thanks in advance.
Your server currently handles only 1 client at a time, use threads for each client, Modify your server code like this:-
public static void main(String[] args) throws IOException
{
ServerSocket s1 = new ServerSocket(40021);
while (true)
{
ss = s1.accept();
Thread t = new Thread()
{
public void run()
{
try
{
String command, temp;
Scanner sc = new Scanner(ss.getInputStream());
while (sc.hasNextLine())
{
command = sc.nextLine();
temp = command + " this is what you said.";
PrintStream p = new PrintStream(ss.getOutputStream());
p.println(temp);
}
} catch (IOException e)
{
e.printStackTrace();
}
}
};
t.start();
}
}

Categories

Resources