I have a classic client/server set up to take in a simple math problem from the client, calculate the result in the server and then send the result back to all connected clients. But on the client side it seems like I'm missing a read somewhere; the messages from first client are only returned to the second client after I input something into the second client and vice versa. I want to be able to send all messages to each client without having to input something first.
Sever code:
import java.net.*;
import java.util.*;
import java.io.*;
public class EchoServer2 extends Thread{
protected Socket clientSocket;
static String [] logs = new String[100];
private static ArrayList<PrintWriter> writers = new ArrayList<PrintWriter>();
static int arrayPos = 0;
static int i;
static String message;
public static void main(String[] args) throws IOException{
ServerSocket serverSocket = null;
try{
serverSocket = new ServerSocket(10008);
System.out.println ("Connection Socket Created");
try {
while (true)
{
System.out.println ("Waiting for Connection");
new EchoServer2 (serverSocket.accept());
}
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
}
catch (IOException e)
{
System.err.println("Could not listen on port: 10008.");
System.exit(1);
}
finally{
try{
serverSocket.close();
}
catch (IOException e)
{
System.err.println("Could not close port: 10008.");
System.exit(1);
}
}
}
private EchoServer2 (Socket clientSoc){
clientSocket = clientSoc;
start();
}
public void run(){
System.out.println ("New Communication Thread Started");
try{
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
writers.add(out);
BufferedReader in = new BufferedReader(new InputStreamReader( clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) { //reading
logs[arrayPos] = inputLine; //keep record of all commands sent to server
arrayPos++; //update array position
if (inputLine.equals("Bye.")) //break if client enters 'Bye."
break;
if(inputLine.equals("Logs.")){ //print out contents of logs if any client enters 'Logs'
for(i=0; i<arrayPos; i++){
System.out.println("Log"+ i + ": " + logs[i]);
out.println("Log"+ i + ": " + logs[i]);
}
break;
}
int x, y, result;
String num1, num2, operator;
String [] splitStrings = inputLine.split(" ");
num1 = splitStrings[0];
x = Integer.parseInt(num1);
operator = splitStrings[1];
num2 = splitStrings[2];
y = Integer.parseInt(num2);
switch(operator){
case "+":
result = x + y;
System.out.println ("Server: " + result);
out.println(result);
for (PrintWriter writer : writers) {
if (writer == out)
continue;
writer.println(result);
}
break;
case "-":
result = x - y;
System.out.println ("Server: " + result);
out.println(result);
for (PrintWriter writer : writers) {
if (writer == out)
continue;
writer.println(result);
}
break;
case "*":
result = x * y;
System.out.println ("Server: " + result);
out.println(result);
for (PrintWriter writer : writers) {
if (writer == out)
continue;
writer.println(result);
}
break;
case "/":
result = x / y;
System.out.println ("Server: " + result);
out.println(result);
for (PrintWriter writer : writers) {
if (writer == out)
continue;
writer.println(result);
}
break;
default:
System.out.println("Please enter a more simple equation using one of the 4 main operators i.e. '+, -, *, /'");
break;
}
}
out.flush();
out.close();
in.close();
clientSocket.close();
}
catch (IOException e){
System.err.println("Problem with Communication Server");
System.exit(1);
}
}
}
Client code:
import java.io.*;
import java.net.*;
public class EchoClient{
public static void main(String[] args) throws IOException{
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " + serverHostname + " on port 10008.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try{
// echoSocket = new Socket("taranis", 7);
echoSocket = new Socket(serverHostname, 10008);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
}catch (UnknownHostException e){
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e){
System.err.println("Couldn't get I/O for " + "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
System.out.println ("Type Message (\"Bye.\" to quit)");
System.out.println("Enter a simple math equation i.e. 2 + 2 separated by a space…");
while ((userInput = stdIn.readLine()) != null){
out.println(userInput);
userInput = in.readLine();
System.out.println("echo: " + userInput);
while(in.ready()){
userInput = in.readLine();
System.out.println("echo: " + userInput);
}
System.out.println("Enter a simple math equation e.g. 2 + 2 separated by a space…");
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
There's quite a few answers on this topic but none seems to work for the way I'm doing it.
All suggestions appreciated.
** I know my code isn't very elegant at the moment but at this stage it's just a case of getting it working and then tidying it up from there.
Solved
The while loop on the client side needed to be altered as so
while(true){
if(userInput == null){
System.out.println("Input is null");
}
if(userInput.equals("Bye.")){
break;
}
if(stdIn.ready()){//(userInput = stdIn.readLine()) != null){
userInput = stdIn.readLine();
out.println(clientID + "\t" + userInput);
userInput = in.readLine();
System.out.println("echo: " + userInput);
System.out.println("Enter a simple math equation e.g. 2 + 2 separated by a space…");
out.flush();
}
else if(in.ready()){
userInput = in.readLine();
System.out.println("echo: " + userInput);
//System.out.println("Enter a simple math equation e.g. 2 + 2 separated by a space…");
out.flush();
}
}
I've also made some other adjustments to the code hence why there's added variables etc!
You need to handle input and output concurrently. One option would be to use separate threads.
Right now your clients and server walk in lock step blocking on input from one to the other in sequence.
This multithreading needs to be on both the server and the client. The server will need two threads per connected client (one for input, one for output) and the clients will need the same but only for the single connection to the server.
Related
I got a problem with my university task.
How to start program: type 1 to create a file then write down the name of text file and fill it with words. After that press enter 2 times and you will get my problem -> NoSuchElementException.
I tried to fix this problem by creating different types of loops or changing the structure of the project, but still don`t know how to fix it. I just stuck and wasted some time on this problem. If someone more knowledgeable could help me out it would be wonderful.
My code all in one class:
import java.io.*;
import java.util.Scanner;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
showMenu();
}
static void showMenu() throws IOException {
menuOptions();
Scanner scan = new Scanner(System.in);
int userMenuInput = 0;
if (scan.hasNextLine()) {
try {
userMenuInput = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
while (true) {
switch (userMenuInput) {
case 1:
System.out.println("Create a file");
String userFileName = scan.nextLine();
createFile(userFileName + ".txt");
break;
case 2:
System.out.println("Delete a file");
String userDeleteFile = scan.nextLine();
deleteFile(userDeleteFile);
break;
case 3:
System.out.println("Write to a file");
break;
case 4:
System.out.println("Exit from program");
System.exit(0);
break;
default:
System.out.println("Please type from 1 to 4!");
}
}
}
private static void createFile(String fileName){
System.out.println(System.getProperty("user.dir"));
File myFile = new File(System.getProperty("user.dir") + "\\" + fileName);
try {
myFile.createNewFile();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Create PrintWriter to write to file
PrintWriter out = new PrintWriter(new FileWriter(myFile));
String s;
System.out.print("Enter text: ");
while ((s = in.readLine()) != null && (s.length() != 0)) {
out.println(s);
}
in.close(); // Close reader from input
out.close(); // Close writer to file
} catch (IOException e) {
System.out.println("File writing failed!");
}
System.out.println(myFile.getAbsolutePath());
}
private static void deleteFile(String fileNameToDelete){
try{
System.out.println("Enter file name to delete: ");
File sourceFile = new File(fileNameToDelete+".txt");
sourceFile.delete();
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
private static void menuOptions(){
System.out.println("Choose from these choices");
System.out.println("-------------------------\n");
System.out.println("1 - Create file");
System.out.println("2 - Delete file");
System.out.println("3 - Write to file");
System.out.println("4 - Quit");
System.out.println();
}
}
to add to Ryans answer, the exception comes from the fact that closing any object making use of the input/output stream doesn't really close that object, but the entire input/output stream. A dirty fix would simply be NOT to close them. so change your method createFile from:
private static void createFile(String fileName){
System.out.println(System.getProperty("user.dir"));
File myFile = new File(System.getProperty("user.dir") + "\\" + fileName);
try {
myFile.createNewFile();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Create PrintWriter to write to file
PrintWriter out = new PrintWriter(new FileWriter(myFile));
String s;
System.out.print("Enter text: ");
while ((s = in.readLine()) != null && (s.length() != 0)) {
out.println(s);
}
in.close(); // Close reader from input
out.close(); // Close writer to file
} catch (IOException e) {
System.out.println("File writing failed!");
}
System.out.println(myFile.getAbsolutePath());
}
to:
private static void createFile(String fileName){
System.out.println(System.getProperty("user.dir"));
File myFile = new File(System.getProperty("user.dir") + "\\" + fileName);
try {
myFile.createNewFile();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Create PrintWriter to write to file
PrintWriter out = new PrintWriter(new FileWriter(myFile));
String s;
System.out.print("Enter text: ");
while ((s = in.readLine()) != null && (s.length() != 0)) {
out.println(s);
}
//were close used to be
} catch (IOException e) {
System.out.println("File writing failed!");
}
System.out.println(myFile.getAbsolutePath());
}
I will stess that this is NOT ideal. You should do what Ryan said and make it so you only use use a single System.in reader. Doing that is your job, not mine. But if this is just to get something working so you can submit an assignment on time, it will work.
Another issue is that the prompt asking for a menu option is outside of the while loop. This means that it will accept only one input, then get stuck in an infinite loop. You could move that into the loop, but a cleaner alternative is to put all of the menu logic into the menuOption method, pass a reference of the Scanner to that method, and have it return an int for your switch.
for example:
menuOption():
private static int menuOptions(Scanner scan){
System.out.println("Choose from these choices");
System.out.println("-------------------------\n");
System.out.println("1 - Create file");
System.out.println("2 - Delete file");
System.out.println("3 - Write to file");
System.out.println("4 - Quit");
System.out.println();
if (scan.hasNextLine()) {
try {
return Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
return 0;
}
showMenu():
static void showMenu() throws IOException {
Scanner scan = new Scanner(System.in);
while (true) {
switch (menuOptions(scan)) {
case 1:
System.out.println("Create a file");
String userFileName = scan.nextLine();
createFile(userFileName + ".txt");
break;
case 2:
System.out.println("Delete a file");
String userDeleteFile = scan.nextLine();
deleteFile(userDeleteFile);
break;
case 3:
System.out.println("Write to a file");
break;
case 4:
System.out.println("Exit from program");
System.exit(0);
break;
default:
System.out.println("Please type from 1 to 4!");
}
}
}
all of those changes lead to this as the final code:
import java.io.*;
import java.util.Scanner;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
showMenu();
}
static void showMenu() throws IOException {
Scanner scan = new Scanner(System.in);
while (true) {
switch (menuOptions(scan)) {
case 1:
System.out.println("Create a file");
String userFileName = scan.nextLine();
createFile(userFileName + ".txt");
break;
case 2:
System.out.println("Delete a file");
String userDeleteFile = scan.nextLine();
deleteFile(userDeleteFile);
break;
case 3:
System.out.println("Write to a file");
break;
case 4:
System.out.println("Exit from program");
System.exit(0);
break;
default:
System.out.println("Please type from 1 to 4!");
}
}
}
private static void createFile(String fileName){
System.out.println(System.getProperty("user.dir"));
File myFile = new File(System.getProperty("user.dir") + "\\" + fileName);
try {
myFile.createNewFile();
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
// Create PrintWriter to write to file
PrintWriter out = new PrintWriter(new FileWriter(myFile));
String s;
System.out.print("Enter text: ");
while ((s = in.readLine()) != null && (s.length() != 0)) {
out.println(s);
}
//were close used to be
} catch (IOException e) {
System.out.println("File writing failed!");
}
System.out.println(myFile.getAbsolutePath());
}
private static void deleteFile(String fileNameToDelete){
try{
System.out.println("Enter file name to delete: ");
File sourceFile = new File(fileNameToDelete+".txt");
sourceFile.delete();
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
private static int menuOptions(Scanner scan){
System.out.println("Choose from these choices");
System.out.println("-------------------------\n");
System.out.println("1 - Create file");
System.out.println("2 - Delete file");
System.out.println("3 - Write to file");
System.out.println("4 - Quit");
System.out.println();
if (scan.hasNextLine()) {
try {
return Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
return 0;
}
}
Remember to close scan in your quit method.
I am new to java and I was given 3 files but I do not know how to compile them to get them to work together.
Here are the files:
GetBurnRate.java
import java.io.*;
public class GetBurnRate{
public static void main(String[] args){
//Send welcome message
System.out.println("#Welcome to Lunar Lander");
try{
//Begin reading from System input
BufferedReader inputReader =
new BufferedReader(new InputStreamReader(System.in));
//Set initial burn rate to 0
int burnRate = 0;
do{
//Prompt user
System.out.println("#Enter burn rate or <0 to quit:");
//Read user response
try{
String burnRateString = inputReader.readLine();
burnRate = Integer.parseInt(burnRateString);
//Send user-supplied burn rate to next filter
System.out.println("%" + burnRate);
} catch(NumberFormatException nfe){
System.out.println("#Invalid burn rate.");
}
}
while(burnRate >= 0);
inputReader.close();
} catch(IOException ioe){
ioe.printStackTrace();
}
}
}
CalcNewValues.java
import java.io.*;
public class CalcNewValues{
public static void main(String[] args){
//Initialize values
final int GRAVITY = 2;
int altitude = 1000;
int fuel = 500;
int velocity = 70;
int time = 0;
try{
BufferedReader inputReader = new
BufferedReader(new InputStreamReader(System.in));
//Print initial values
System.out.println("%a" + altitude);
System.out.println("%f" + fuel);
System.out.println("%v" + velocity);
System.out.println("%t" + time);
String inputLine = null;
do{
inputLine = inputReader.readLine();
if((inputLine != null) &&
(inputLine.length() > 0)){
if(inputLine.startsWith("#")){
//This is a status line of text, and
//should be passed down the pipeline
System.out.println(inputLine);
}
else if(inputLine.startsWith("%")){
//This is an input burn rate
try{
int burnRate =
Integer.parseInt(inputLine.substring(1));
if(altitude <= 0){
System.out.println("#The game is over.");
}
else if(burnRate > fuel){
System.out.println("#Sorry, you don't" +
"have that much fuel.");
}
else{
//Calculate new application state
time = time + 1;
altitude = altitude - velocity;
velocity = ((velocity + GRAVITY) * 10 -
burnRate * 2) / 10;
fuel = fuel - burnRate;
if(altitude <= 0){
altitude = 0;
if(velocity <= 5){
System.out.println("#You have" +
"landed safely.");
}
else{
System.out.println("#You have" +
"crashed.");
}
}
}
//Print new values
System.out.println("%a" + altitude);
System.out.println("%f" + fuel);
System.out.println("%v" + velocity);
System.out.println("%t" + time);
}
catch(NumberFormatException nfe){
}
}
}
}
while((inputLine != null) && (altitude > 0));
inputReader.close();
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}
DisplayValues.java
import java.io.*;
public class DisplayValues{
public static void main(String[] args){
try{
BufferedReader inputReader = new
BufferedReader(new InputStreamReader(System.in));
String inputLine = null;
do{
inputLine = inputReader.readLine();
if((inputLine != null) &&
(inputLine.length() > 0)){
if(inputLine.startsWith("#")){
//This is a status line of text, and
//should be passed down the pipeline with
//the pound-sign stripped off
System.out.println(inputLine.substring(1));
}
else if(inputLine.startsWith("%")){
//This is a value to display
if(inputLine.length() > 1){
try{
char valueType = inputLine.charAt(1);
int value =
Integer.parseInt(inputLine.substring(2));
switch(valueType){
case 'a':
System.out.println("Altitude: " +
value);
break;
case 'f':
System.out.println("Fuel remaining: " +
value);
break;
case 'v':
System.out.println("Current Velocity: "
+ value);
break;
case 't':
System.out.println("Time elapsed: " +
value);
break;
}
}
catch(NumberFormatException nfe){
}
}
}
}
}
while(inputLine != null);
inputReader.close();
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}
Then I am supposed to change GetCalcNewValues.java and translate it to C++ and get it to run as so:
|GetBurnRate.java | GetCalcNewValues.cpp | DisplayValues.java
I only need to know how to properly compiler these, I can do the translation.
To compile a java program with main file GetBurnRate.java type the following into a console (You will need a java compiler installed)
javac GetBurnRate.java
To compile a c++ program you will need a c++ compile installed such as gcc or clang.
For gcc type the following into a console
g++ GetCalcNewValues.cpp -o GetCalcNewValues.exe
For clang
clang++ GetCalcNewValues.cpp -o GetCalcNewValues.exe
If you aren't using windows the file extension for the compiled c++ program probably won't be exe.
To run the programs giving the output from the first as the input to the next use
java GetBurnRate | GetCalcNewValues | java DisplayValues
I'm confused with how I'm wanting clients to talk to the server in order. For example, I'm creating a multiplayer tic tac toe game, where 2 clients will connect to the game server. The clients then take turns to put in the coordinates of the x's. However, when I use a break on my while loop, it only lets them enter once, before disconnecting the socket. How do I do it such that the clients are just temporarily blocked while the other client answers?
EDIT: I do not intend to use multithreading for this purpose.
Server (truncated for reading purposes):
try {
while (true) {
System.out.println("Awaiting connection!");
Socket clientSocket = server.accept();
System.out.println("Player " + noOfPlayers + " has connected!");
noOfPlayers ++;
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while (!newGame.checkWinner()) {
out.println(newGame.currentPlayer());
input = in.readLine();
x = Integer.parseInt(input.split("\\,+")[0]);
y = Integer.parseInt(input.split("\\,+")[1]);
newGame.addPoint(x, y);
out.println("Moved");
if (newGame.checkWinner()) {
System.out.println("The winner is " + newGame.currentPlayer());
out.println("The winner is " + newGame.currentPlayer());
server.close();
break;
}
else if (newGame.boardFilledUp()) {
newGame.loadBoard();
out.println("It's a draw!");
server.close();
break;
}
newGame.loadBoard();
newGame.changePlayer();
break;
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
Client (truncated for reading purposes):
while (true) {
PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
// Read input from server
BufferedReader in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
// Read input from client
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter your coordinates in x,y form: ");
String userInput;
char serverOutput;
serverOutput = in.readLine().charAt(0);
System.out.println("Current player is " + serverOutput);
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("You sent: " + userInput);
}
break;
}
Figured out the problem. I didn't flush the PrintWriter.
I'm having trouble with my java client/server program using sockets. When I choose an option from the looping menu, it only works sometimes (rarely more than once), and if the output from the server has quite a few lines, the client either doesn't receive them all or doesn't print them all.
I'm very new to this, so anything would be helpful!
Client:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class client {
static String hostname = null;
static Scanner console = new Scanner(System.in);
static int myPort = 2123;
static String userChoice = null;
static String command = null;
public static void main(String[] args) throws IOException {
System.out.print("Please enter hostname: ");
hostname = console.nextLine();
if (args.length > 0)
hostname = args[0];
System.out.println ("Attemping to connect to host " +
hostname + " on port " + myPort + ".");
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
socket = new Socket(hostname, myPort);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + hostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Can't connect to: " + hostname);
System.exit(1);
}
while(true)
{
displayMenu();
saveChoice();
if(command != null){
out.println(command);
while((in.readLine()) != null)
{
System.out.println(in.readLine());
}
}
}
}
public static void displayMenu()
{
System.out.println(" ");
System.out.println("1. Host Current Date and Time");
System.out.println("2. Host uptime");
System.out.println("3. Host memory use");
System.out.println("4. Host Netstat");
System.out.println("5. Host current users");
System.out.println("6. Host running processes");
System.out.println("7. Quit ");
System.out.println(" ");
System.out.print("Your choice: ");
userChoice = console.nextLine();
}
public static void saveChoice()
{
switch (userChoice)
{
case "1":
command = "date";
break;
case "2":
command = "systeminfo | find \"System Boot Time\"";
break;
case "3":
command = "systeminfo | find \"Virtual Memory: In Use\"";
break;
case "4":
command = "netstat";
break;
case "5":
command = "netuser";
break;
case "6":
command = "tasklist";
break;
case "7":
System.out.println("Goodbye");
System.exit(0);
break;
default:
System.out.print("That is not a choice. Please enter an option between 1-7.");
}
}
}
Server:
import java.net.*;
import java.io.*;
public class server
{
static int count = 0;
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(2123);
}
catch (IOException e)
{
System.err.println("Could not listen on port: 2123.");
System.exit(1);
}
Socket clientSocket = null;
System.out.println ("Waiting for connection.....");
try {
clientSocket = serverSocket.accept();
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
System.out.println ("Connection successful");
System.out.println ("Waiting for input.....");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("cmd /c " + inputLine);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
// read the output from the command
String s = null;
while ((s = stdInput.readLine()) != null)
{
out.println(s);
count++;
}
System.out.print("Lines sent to client: " + count);
}
}
}
I am having a problem with a client-server application. The program runs correctly through until the second time the client must input data. Upon debugging the code it appears that the client always crashes on the line linesIn = din.readInt(); on the second iteration through the loop.
as suggested I added a try catch block around the integer parsing and it seems to have helped move the program further along but now when run the program will only give the correct output to the user once and after that will display the list of options available twice and then not accept any further input
The following output is displayed in the client:
The address and hostname are: BOO-PC/192.168.0.8
The Hostname: BOO-PC
The Address only: 192.168.0.8
Server: Welcome please make your selection from the options below
Server: 1: make a booking
Server: 2: cancel a booking
Server: 3: view available films
Server: 4: logout
Client:
3
Server: Title :Film1
Server: Time : 10.3
Server: Date : 10 7 2013
Server: Price : 5.0
Server: Referance Number : 55
Server:
Client:
Server:
and this error on the server
Exception in thread "serverThread" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:527)
at systemssoftwarebookingsystem.serverThread.run(serverThread.java:45)
server thread code:
package systemssoftwarebookingsystem;
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class serverThread extends Thread
{
private Socket socket = null;
private PrintWriter write = null;
private BufferedReader read = null;
public serverThread(Socket socket)
{
super("serverThread");
this.socket = socket;
}
public void run()
{
Scanner in;
in = new Scanner(System.in);
char[] input;
int inputReferance = 0;
int inputSeatAmount = 0;
boolean filmFound = false;
boolean exit = false;
try
{
read = new BufferedReader(new InputStreamReader(socket.getInputStream()));
write = new PrintWriter(new DataOutputStream(socket.getOutputStream()));
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
int choice = 0;
while (exit == false)
{
choice = 0;
out.writeInt(5);
write.println("Welcome please make your selection from the options below \n 1: make a booking \n 2: cancel a booking \n 3: view available films \n 4: logout");
write.flush();
input = new char[1];
read.read(input);
choice = Integer.parseInt(new String(input));
switch (choice)
{
case 1:
{
Film tempFilm = null;
out.writeInt(1);
write.println("Please enter the referance number of the film you wish to watch");
write.flush();
read.read(input);
inputReferance = Integer.parseInt(new String(input));
for (Film s : server.filmList)
{
if (s.referanceNumber == inputReferance)
{
filmFound = true;
tempFilm = s;
}
}
if (filmFound == false)
{
out.writeInt(1);
write.println("Sorry. That referance number was not recognised. Please try again");
write.flush();
break;
}
if (filmFound == true)
{
out.writeInt(1);
write.println("Please enter the numbe rof seats you wish to book");
write.flush();
inputSeatAmount = read.read(input);
inputSeatAmount = Integer.parseInt(new String(input));
if (tempFilm.seatsAvailable < inputSeatAmount)
{
out.writeInt(2);
write.println("Sorry. There are not enough seats available for that film \n Only " + tempFilm.seatsAvailable + "seats are available");
write.flush();
break;
}
server.bookings.add(new Booking(inputReferance, server.bookingNumber, inputSeatAmount));
server.bookingNumber++;
out.writeInt(1);
write.println("booking placed successfully");
write.flush();
break;
}
}
case 2:
{
out.writeInt(1);
write.println("Please enter the booking number of the booking you wish to cancel");
write.flush();
inputReferance = read.read(input);
inputReferance = Integer.parseInt(new String(input));
for (Booking s : server.bookings)
{
if (s.bookingNumber == inputReferance)
{
filmFound = true;
break;
}
}
if (filmFound == false)
{
out.writeInt(1);
write.println("Sorry. That booking number was not recognised. Please try again");
write.flush();
break;
}
server.bookings.remove(inputReferance);
out.writeInt(1);
write.println("booking cancelled");
write.flush();
break;
}
case 3:
{
for (Film s : server.filmList)
{
out.writeInt(6);
write.println("Title :" + s.name + "\n Time : " + s.showingTime + "\n Date : " + s.day + " " + s.month + " " + s.year + "\n Price : " + s.price + "\n Referance Number : " + s.referanceNumber + "\n");
write.flush();
}
out.writeInt(1);
write.println("end of list");
write.flush();
break;
}
case 4:
{
exit = true;
out.writeInt(1);
write.println("Bye.");
write.flush();
break;
}
}
}
socket.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
client code:
package syssoftclient;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Syssoftclient
{
public static void main(String[] args) throws IOException
{
try
{
InetAddress internetAddress = InetAddress.getLocalHost();
System.out.println("The address and hostname are: " + internetAddress);
System.out.println("The Hostname: " + internetAddress.getHostName());
System.out.println("The Address only: " + internetAddress.getHostAddress());
} catch (UnknownHostException e)
{
System.err.println("Connection problem " + e);
}
Socket SocketC = null;
PrintWriter out = null;
BufferedReader in = null;
boolean exit = false;
try
{
SocketC = new Socket(InetAddress.getLocalHost().getHostName(), 8888);
out = new PrintWriter(SocketC.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(SocketC.getInputStream()));
} catch (UnknownHostException e)
{
System.err.println("Host not recognised");
System.exit(1);
} catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection");
System.exit(1);
}
String fromServer = null;
String fromUser = null;
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
DataInputStream din;
din = new DataInputStream(SocketC.getInputStream());
int lineCount = 0;
int linesIn = 0;
while (exit == false)
{
lineCount = 0;
linesIn = din.readInt();
while (lineCount < linesIn)
{
fromServer = in.readLine();
System.out.println("Server: " + fromServer);
lineCount++;
}
if ("Bye.".equals(fromServer))
{
System.out.println("Quitting");
exit = true;
break;
}
System.out.println("Client: ");
fromUser = stdIn.readLine(); //reads userinput
if (fromUser != null)
{
out.println(fromUser); //sends user input to the server
out.flush();
}
if ("exit".equals(fromUser))
{
exit = true;
}
}
out.close();
in.close();
stdIn.close();
SocketC.close(); //close everything before ending program
}
}
Based on your updated question, I think there error is here:
choice = Integer.parseInt(new String(input));
I'm not sure as I don't know exactly what line number 45 is.
You're trying to parse a new line character as an integer. This is throwing an exception, causing the server to exit its while loop, and the program to close.
So, wrap your parsing routines in try/catch blocks and handle them. The error should go away then.