У меня проблема с клиент-серверным приложением. Программа работает корректно до тех пор, пока клиент не должен будет вводить данные во второй раз. При отладке кода выясняется, что клиент всегда аварийно завершает работу в строке linesIn = din.readInt();
на второй итерации цикла.
как было предложено, я добавил блок try catch вокруг синтаксического анализа целых чисел, и, похоже, это помогло продвинуть программу дальше, но теперь при запуске программа выдаст правильный вывод пользователю только один раз, а после этого дважды отобразит список доступных параметров. а затем не принимать никаких дальнейших входных данных
В клиенте отображается следующий вывод:
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:
и эта ошибка на сервере
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)
код потока сервера:
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();
}
}
}
код клиента:
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
}
}