Java programming accessing object variables - java

Helo, there are 3 files, CustomerClient.java, CustomerServer.java and Customer.java
PROBLEM: In the CustomerServer.java file, i get an error when I compile the CustomerServer.java at line : System.out.println(a[k].getName());
ERROR:
init:
deps-jar:
Compiling 1 source file to C:\Documents and Settings\TLNA\My Documents\NetBeansProjects\Server\build\classes
C:\Documents and Settings\TLNA\My Documents\NetBeansProjects\Server\src\CustomerServer.java:44: cannot find symbol
symbol : method getName()
location: class Customer
System.out.println(a[k].getName());
1 error
BUILD FAILED (total time: 0 seconds)
CustomerClient.java
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CustomerClient extends JApplet {
private JTextField jtfName = new JTextField(32);
private JTextField jtfSeatNo = new JTextField(32);
// Button for sending a student to the server
private JButton jbtRegister = new JButton("Register to the Server");
// Indicate if it runs as application
private boolean isStandAlone = false;
// Host name or ip
String host = "localhost";
public void init() {
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(2, 1));
p1.add(new JLabel("Name"));
p1.add(jtfName);
p1.add(new JLabel("Seat No."));
p1.add(jtfSeatNo);
add(p1, BorderLayout.CENTER);
add(jbtRegister, BorderLayout.SOUTH);
// Register listener
jbtRegister.addActionListener(new ButtonListener());
// Find the IP address of the Web server
if (!isStandAlone) {
host = getCodeBase().getHost();
}
}
/** Handle button action */
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
// Establish connection with the server
Socket socket = new Socket(host, 8000);
// Create an output stream to the server
ObjectOutputStream toServer =
new ObjectOutputStream(socket.getOutputStream());
// Get text field
String name = jtfName.getText().trim();
String seatNo = jtfSeatNo.getText().trim();
// Create a Student object and send to the server
Customer s = new Customer(name, seatNo);
toServer.writeObject(s);
} catch (IOException ex) {
System.err.println(ex);
}
}
}
/** Run the applet as an application */
public static void main(String[] args) {
// Create a frame
JFrame frame = new JFrame("Register Student Client");
// Create an instance of the applet
CustomerClient applet = new CustomerClient();
applet.isStandAlone = true;
// Get host
if (args.length == 1) {
applet.host = args[0];
// Add the applet instance to the frame
}
frame.add(applet, BorderLayout.CENTER);
// Invoke init() and start()
applet.init();
applet.start();
// Display the frame
frame.pack();
frame.setVisible(true);
}
}
CustomerServer.java
import java.io.*;
import java.net.*;
public class CustomerServer {
private String name;
private int i;
private ObjectOutputStream outputToFile;
private ObjectInputStream inputFromClient;
public static void main(String[] args) {
new CustomerServer();
}
public CustomerServer() {
Customer[] a = new Customer[30];
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
System.out.println("Server started ");
// Create an object ouput stream
outputToFile = new ObjectOutputStream(
new FileOutputStream("student.dat", true));
while (true) {
// Listen for a new connection request
Socket socket = serverSocket.accept();
// Create an input stream from the socket
inputFromClient =
new ObjectInputStream(socket.getInputStream());
// Read from input
//Object object = inputFromClient.readObject();
for (int k = 0; k <= 2; k++) {
if (a[k] == null) {
a[k] = (Customer) inputFromClient.readObject();
// Write to the file
outputToFile.writeObject(a[k]);
//System.out.println("A new student object is stored");
System.out.println(a[k].getName());
break;
}
if (k == 2) {
//fully booked
outputToFile.writeObject("All seats are booked");
break;
}
}
}
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
inputFromClient.close();
outputToFile.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
Customer.java
public class Customer implements java.io.Serializable {
private String name;
private String seatno;
public Customer(String name, String seatno) {
this.name = name;
this.seatno = seatno;
}
public String getName() {
return name;
}
public String getSeatNo() {
return seatno;
}
}

The build message says its only compiling one source file. Perhaps the Customer class changed to include the getName function and has not been recompiled since.
Did you try compiling all three source files at the same time?

Recompile the Customer.java and make sure you don't have duplicate versions of the class file hanging around. Use debugger (set breakpoint after the customer class de-serialization) for further debugging.

Related

Casting a String to a generic type <T extends Comparable<T>>

I'm writing a GUI client for manipulating and displaying binary trees. The tricky part here is that the trees are of a generic type. I'm in the situation where I have to pass my server a value obtained from a user with the help of Message<T>, which is a Serializable object, storing a request and its value for the server. My problem is that the value of the type T is obtained using JOptionPane.showInputDialog, which returns String.
Is there any way to get the input from the user in the form of the T type or to convert the String to mentioned type?
Main Class:
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
Object[] options = {"Integer", "Double", "String"};
int result = JOptionPane
.showOptionDialog(null, "Please, select the type of the tree:", "Selection of the type",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, null);
switch (result) {
case 0:
MyFrame<Integer> frameInteger = new MyFrame<>("Integer");
frameInteger.setVisible(true);
break;
case 1:
MyFrame<Double> frameDouble = new MyFrame<>("Double");
frameDouble.setVisible(true);
break;
case 2:
MyFrame<String> frameString = new MyFrame<>("String");
frameString.setVisible(true);
default:
throw new IllegalArgumentException("Invalid type.");
}
}
}
JFrame/Client Class:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class MyFrame<T extends Comparable<T>> extends JFrame {
Socket client;
JPanel context = new JPanel();
String address;
ObjectInputStream in;
ObjectOutputStream out;
BinaryTree<T> tree;
boolean result;
String type;
public MyFrame(String type) {
this.type = type;
address = JOptionPane.showInputDialog("Please enter the address and port (e.g. 127.0.0.1:5555)");
try {
client = new Socket(address.split(":")[0], Integer.parseInt(address.split(":")[1]));
in = new ObjectInputStream(client.getInputStream());
out = new ObjectOutputStream(client.getOutputStream());
} catch (Exception e) {
System.err.println("It wasn't possible to obtain the address from the given input.");
}
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(1024, 720);
setLocationRelativeTo(null);
setTitle("Binary Tree Client");
initUI();
}
private void initUI() {
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("File...");
JMenu edit = new JMenu("Edit");
JMenuItem close = new JMenuItem("Close");
JMenuItem insert = new JMenuItem("Insert...");
JMenuItem delete = new JMenuItem("Delete...");
JMenuItem search = new JMenuItem("Search...");
close.addActionListener(e -> System.exit(0));
insert.addActionListener(e -> {
String value = JOptionPane.showInputDialog("Please insert the node value:");
// here is the problem
tree = exchange(new ClientMessage<T>("INSERT", value)).getTree();
});
file.add(close);
edit.add(insert);
edit.add(delete);
edit.add(search);
menuBar.add(file);
menuBar.add(edit);
setJMenuBar(menuBar);
}
public ServerMessage<T> exchange(ClientMessage<T> clientMsg) {
try {
out.writeObject(clientMsg);
return (ServerMessage<T>) in.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
}
ClientMessage Class:
import java.io.Serializable;
public class ClientMessage<T extends Comparable<T>> implements Serializable {
private String request;
private T value;
public ClientMessage(String request, T value) {
this.request = request;
this.value = value;
}
public String getRequest() {
return request;
}
public T getValue() {
return value;
}
}
And the ServerThread Class where I want to use the value:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class ServerThread<T extends Comparable<T>> extends Thread {
BinaryTree<T> tree;
ObjectInputStream in;
ObjectOutputStream out;
Socket client;
public ServerThread(Socket client) {
this.client = client;
}
#Override
#SuppressWarnings("unchecked")
public void run() {
try {
in = new ObjectInputStream(client.getInputStream());
out = new ObjectOutputStream(client.getOutputStream());
ClientMessage<T> request;
ServerMessage<T> response = new ServerMessage<>();
while ((request = (ClientMessage<T>) in.readObject()) != null) {
handleRequest(request, response);
response.setTree(tree);
out.writeObject(response);
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
private void handleRequest(ClientMessage<T> request, ServerMessage<T> response) {
switch (request.getRequest()) {
case "SET":
tree = new BinaryTree<>();
break;
case "INSERT":
tree.insert(request.getValue());
break;
case "DELETE":
tree.delete(request.getValue());
break;
case "SEARCH":
response.setResult(tree.search(request.getValue()));
break;
default:
throw new IllegalArgumentException("Invalid request.");
}
}
}
Change your MyFrame class to accept a Class<T>:
Class<T> type;
public MyFrame(Class<T> type) {
this.type = type;
...
}
and call like:
MyFrame<Integer> frameInteger = new MyFrame<>(Integer.class);
Or, since you don't apparently use the type field, just remove the type field and the constructor parameter, and call like:
MyFrame<Integer> frameInteger = new MyFrame<>();

How to deserialize objects after closing an opening program in Java 11

I have a program in which I am trying to implement saving and loading of obejcts, however I couldn't get the loading to work after the program closes, so effectively only saving and loading works while the program is open, but no data is ever loaded once the program starts. I assume this is something to do with overwiting. I created a test program to see if I could get it to work just using a simple Person class. I store my Peson objects inside an ArrayList and serialize it, then deserialize it. Currently I am storing all loaded Person objects in a JComboBox. I have looked online and could not find anything that will help. Also note I am aware that using serialization is not the best method of saving objects, but it's something suitable to use for my program.
My App Class:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
public class App extends JFrame {
public static JComboBox<Person> peopleBox;
public App(){
try {
Person.peopleList = loadList();
}
catch(IOException | ClassNotFoundException e){
System.out.println(e.getMessage());
}
try {
saveList(Person.peopleList);
}catch (IOException e){
System.out.println(e.getMessage());
}
peopleBox = new JComboBox<>();
peopleBox.setModel(getComboBoxModel(Person.peopleList));
add(peopleBox);
pack();
setSize(600, 400);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public DefaultComboBoxModel<Person> getComboBoxModel(ArrayList<Person> peopleList){
Person[] comboBoxModel = peopleList.toArray(new Person[0]);
return new DefaultComboBoxModel<>(comboBoxModel);
}
public static void saveList(ArrayList<Person> peopleList) throws IOException {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("test.bin"));
objectOutputStream.writeObject(peopleList);
}
public static ArrayList<Person> loadList() throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("test.bin"));
Person.peopleList = (ArrayList<Person>) objectInputStream.readObject();
return Person.peopleList;
}
public static void main(String[] args){
// Person p = new Person("Sean", 22);
try {
saveList(Person.peopleList);
}catch (IOException e){
System.out.println(e.getMessage());
}
App app = new App();
app.pack();
app.setVisible(true);
}
}
Person Class
import java.io.Serializable;
import java.util.ArrayList;
public class Person implements Serializable {
public int age;
public String name;
public static ArrayList<Person> peopleList = new ArrayList<>();
public Person(String name, int age){
this.age = age;
this.name = name;
peopleList.add(this);
for(Person p : peopleList){
System.out.println(p.toString());
}
}
public Person(){
}
public String toString(){
return "Name : " + name + " Age: " + age;
}
}
I expect when I save the list to the "test.bin" file, close the program, then open it again that it will load the list and display the Objects I created before I closed the program. I appreciate any help, thanks.
You are saving an empty list before you load Person from the file.
I suggest this approach:
import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class App extends JFrame {
public static JComboBox<Person> peopleBox;
public App() {
try {
loadList();
} catch (IOException | ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
saveList(Person.peopleList);
} catch (IOException e) {
System.out.println(e.getMessage());
}
setSize(600, 400);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public void updateData(){
peopleBox = new JComboBox<>();
peopleBox.setModel(getComboBoxModel(Person.peopleList));
add(peopleBox);
pack();
}
public DefaultComboBoxModel<Person> getComboBoxModel(ArrayList<Person> peopleList) {
Person[] comboBoxModel = peopleList.toArray(new Person[0]);
return new DefaultComboBoxModel<>(comboBoxModel);
}
public static void saveList(ArrayList<Person> peopleList) throws IOException {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("test.bin"));
objectOutputStream.writeObject(peopleList);
}
public static void loadList() throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("test.bin"));
Person.peopleList.addAll((List<Person>) objectInputStream.readObject());
}
public static void main(String[] args) {
App app = new App();
Person p = new Person("Sean2", 24);
try {
saveList(Person.peopleList);
} catch (IOException e) {
System.out.println(e.getMessage());
}
app.updateData();
app.setVisible(true);
}
}

java.io.EOFException when using sockets with blockchain in java

i have to do a practice in my uni, it must create a blockchain using sockets and serialization in a "simple way". But when exiting the loop (typing "NO") It creates a EOF exception that i cannot solve, while closing the socket(s.close()). i would appreciate some help, i am not vry good at java. here are my classes.
Client
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client implements Runnable{
public static void main(String[] args) throws Exception {
(new Thread(new Client())).start();
}
public static MedicalReport createReport(){
return new MedicalReport(10,"pepe","id","record");
}
#Override
public void run() {
// int port = 12345;
// String computer = "localhost";
try{
Socket s = new Socket("localhost", 12348);
ObjectOutputStream p = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
/* PrintWriter print = new PrintWriter(s.getOutputStream());
print.println("ready");
print.flush();*/
//manda informe al servidor serializado y espera respuesta
boolean stop = false;
while(!stop){
try{
MedicalReport report = createReport();
p.writeObject(report);
p.flush();
p.reset();
System.out.println("Do you want to continue? Yes or No");
Scanner in1 = new Scanner (System.in);
String answer="";
if(in1.hasNextLine())
answer = in1.nextLine();
if(!answer.equalsIgnoreCase("yes")){
System.out.println(report);
stop = true;
}
}
catch(Exception e){
System.out.println(e);
}
}
try{
s.close();
}
catch(Exception e){
System.out.println(e);
}
}catch(Exception e){
System.out.println(e);
}
}
}
SERVER
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
public class Server {
public static void main(String[] args)
throws Exception
{
ArrayList<Block> blockChain = new ArrayList<>();
try{
ServerSocket ss = new ServerSocket(12348);
Socket s = ss.accept();
ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
/* Scanner scanner = new Scanner(s.getInputStream());
String text = scanner.nextLine();*/
int i = 0;
int previousHash = 0;
while (i != 20){
MedicalReport rp = (MedicalReport)in.readObject();
Block block = new Block(rp,previousHash);
blockChain.add(block);
System.out.println("Block " + blockChain.size() + " added to blockchain");
System.out.println(blockChain.get(i));
previousHash = block.getBlockHash();
System.out.println(blockChain);
i++;
}
try{
ss.close();
}
catch(Exception e){
System.out.println(e);
}
}catch(Exception e){
System.out.println(e);
}
}
}
It looks like the error is while closing the socket, any idea?
EDIT REST OF THE CODE
MEDICAL REPORT
import java.io.Serializable;
public class MedicalReport implements Serializable {
private int age;
private String name;
private String id;
private String record;
private static final long serialVersionUID = 1L;
public MedicalReport(){super();}
public MedicalReport(int age, String name, String id, String record) {
super();
this.age = age;
this.name = name;
this.id = id;
this.record = record;
}
public String getRecord(){
return this.record;
}
public String toString(){
return this.name + ". \n" + this.age + ". \n" + this.id + ". \n" + this.record;
}
}
BLOCK
public class Block {
private int blockHash;
private int previousHash;
private MedicalReport report;
//Block Constructor.
public Block(MedicalReport report,int previousHash ) {
this.previousHash = previousHash;
this.report = report;
this.blockHash = report.hashCode();
}
public int getPreviousHash() {
return previousHash;
}
public MedicalReport getReport() {
return report;
}
public int getBlockHash() {
return blockHash;
}
}
EDIT 2
FIRST QUESTION SOLVED. Now i get this error when exiting the loop:
java.net.SocketException: Connection reset by peer: socket write error
readObject() throws EOFEzception when the peer has closed the connection. This is normal. Catch it and stop reading. There is no problem here to solve.
IMPORTANT: As EJP said EOFException is normal and you can control the flow of your code with it but if you still want to know how to do in the way you asked here it is. REMEMBER THIS IS JUST FULFILL YOUR QUESTION AND NOT ADVISED TO DO SO.
On Server Class
Replace
MedicalReport rp = (MedicalReport)in.readObject();
With
MedicalReport rp;
if((rp = (MedicalReport)in.readObject())==null) break;
On Client Class
ADD
p.writeObject(null);
Just above the s.close(); statement
You must know that when a peer close the connection normally then
read() returns -1,
readLine() returns null,
readXXX() throws EOFException for any other XXX
And A write will throw an IOException

Java Client and Server connected but not communicating

so I'm trying to create a Client - Server chat application and I've got the program already written. The client and server connect through a common port(5000) on localhost. The server and client connect (the console confirms this with a system.out) however when I prompt the server to send a println out to the client to prompt the user to enter a username nothing happens. Please help.
Client:
//ChatClient.java
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.Socket;
public class ChatClient {
static JFrame chatWindow = new JFrame("OneOh");
static JTextArea chatArea = new JTextArea(20, 50);
static JTextField textField = new JTextField(40);
static JLabel blankLabel = new JLabel(" ");
static JButton sendButton = new JButton("Send");
static BufferedReader in;
static PrintWriter out;
static JLabel nameLabel = new JLabel(" ");
private Socket soc;
ChatClient()
{
chatWindow.setLayout(new FlowLayout());
chatWindow.add(nameLabel);
chatWindow.add(new JScrollPane(chatArea));
chatWindow.add(blankLabel);
chatWindow.add(textField);
chatWindow.add(sendButton);
chatWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
chatWindow.setSize(475, 500);
chatWindow.setVisible(true);
textField.setEditable(false);
chatArea.setEditable(false);
sendButton.addActionListener(new Listener());
textField.addActionListener(new Listener());
}
void startChat() throws Exception
{
String ipAddress = JOptionPane.showInputDialog(
chatWindow,
"Enter IP Address:",
"IP Address Required",
JOptionPane.PLAIN_MESSAGE);
soc = new Socket(ipAddress, 5000);
in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
out = new PrintWriter(soc.getOutputStream(), true);
while (true)
{
String str = in.readLine();
if (str.equals("NAMEREQUIRED"))
{
String name = JOptionPane.showInputDialog(
chatWindow,
"Enter a unique name:",
"Name Required!!",
JOptionPane.PLAIN_MESSAGE);
out.println(name);
}
else if(str.equals("NAMEALREADYEXISTS"))
{
String name = JOptionPane.showInputDialog(
chatWindow,
"Enter another name:",
"Name Already Exits!!",
JOptionPane.WARNING_MESSAGE);
out.println(name);
}
else if (str.startsWith("NAMEACCEPTED"))
{
textField.setEditable(true);
nameLabel.setText("You are logged in as: "+str.substring(12));
}
else
{
chatArea.append(str + "\n");
}
}
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
ChatClient client = new ChatClient();
client.startChat();
}
}
class Listener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
ChatClient.out.println(ChatClient.textField.getText());
ChatClient.textField.setText("");
}
}
server:
//ChatServer.java
import java.io.*;
import java.net.*;
import java.util.ArrayList;
public class ChatServer {
static ArrayList<String> userNames = new ArrayList<String>();
static ArrayList<PrintWriter> printWriters = new ArrayList<PrintWriter>();
public static void main(String[] args) throws Exception{
System.out.println("Waiting for clients...");
#SuppressWarnings("resource")
ServerSocket ss = new ServerSocket(5000);
while (true)
{
Socket soc = ss.accept();
System.out.println("Connection established");
ConversationHandler handler = new ConversationHandler(soc);
handler.start();
}
}
}
class ConversationHandler extends Thread
{
Socket socket;
BufferedReader in;
PrintWriter out;
String name;
PrintWriter pw;
static FileWriter fw;
static BufferedWriter bw;
public ConversationHandler(Socket socket) throws IOException {
this.socket = socket;
fw = new FileWriter("C:\\Users\\Edoardo Sella\\Desktop\\ChatServer-Logs.txt",true);
bw = new BufferedWriter(fw);
pw = new PrintWriter(bw);
}
public void run()
{
try
{
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
while (true)
{
int _count = 0;
if(_count > 0)
{
out.println("NAMEALREADYEXISTS");
}
else
{
out.println("NAMEREQUIRED");
}
name = in.readLine();
if (name == null)
{
return;
}
if (!ChatServer.userNames.contains(name))
{
ChatServer.userNames.add(name);
break;
}
_count++;
}
out.println("NAMEACCEPTED"+name);
ChatServer.printWriters.add(out);
while (true)
{
String message = in.readLine();
if (message == null)
{
return;
}
pw.println(name + ": " + message);
for (PrintWriter writer : ChatServer.printWriters) {
writer.println(name + ": " + message);
}
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}
I'm really confused as to why the Client doesn't receive the out.println command any help is appreciated thanks!
You have multiple errors here.
The most important one is about the logic: on the server side, you first listen to an incoming message from the client:
name = in.readLine();
which is blocking. In the client side, you do exactly the same:
String str = in.readLine();
So, both sides are waiting for an incoming message, which will never come. Simply add something like:
out.println("hello")
at the beginning of the run method of ConversationHandler and you will see your message is actually correctly received by the client.
You absolutely need to alternate here, i.e. choose one to send a message first.
Also, don't forget to flush the output stream, or even better use:
out = new PrintWriter(socket.getOutputStream(), true);
Notice the true: it will make the printwriter autoflush, i.e. always send messages right away (vs keeping them in cache), even if the message is small. See this question for more info about flushing.
Some additional remarks:
use blank lines wisely: addind a blank line between every statement makes the code very large and difficult to read. Instead, use a blank lines to separate logical blocks
in the conversation handler (run method), you have the line:
int _count = 0;
if (_count > 0)
it is easy to see that the condition will always be true
try not to hardcode file paths (new FileWriter("C:\\Users\\Edoardo Sella\\Desktop\\ChatServer-Logs.txt", true);. Prefer relative file paths or at least put them inside a global final variable easy to find and change

Error when compiling cannont access class

Trying to compilie this AuctionClientMain.java and this is the error I get and can't figur it out:
AuctionClientMain.java:16: cannot access AuctionClient
bad class file: .\AuctionClient.class
class file contains wrong class: Assignment.AuctionClient
Please remove or make sure it appears in the correct subdirectory of the classpath.
AuctionClient a = new AuctionClient(args[0],args[1],port);
I have included AuctionClientMain.java
import Auction.*;
import java.io.*;
public class AuctionClientMain
{
//Create the client
public static void main (String args[]) throws IOException
{
if(args.length!=3)
{
throw new RuntimeException ("Syntax: java AuctionClient <name> <serverhost> <port>");
}
//Convert port taken in as string to an integer
int port = Integer.parseInt(args[2]);
AuctionClient a = new AuctionClient(args[0],args[1],port);
}
}
And the Auction Client
package Auction;
import java.io.*;
import java.net.*;
public class AuctionClient
{
public AuctionGui gui;
private Socket socket;
private DataInputStream dataIn;
private DataOutputStream dataOut;
//Auction Client constructor String name used as identifier for each client to allow server to pick the winning bidder
public AuctionClient(String name,String server, int port)
{
//Create a new gui
gui = new AuctionGui("Bidomatic 5000");
//Add the key listener to the input field
gui.input.addKeyListener (new EnterListener(this,gui));
//Add the exit listener to the window
gui.addWindowListener(new ExitListener(this));
try
{
//Create a new socket with server name and port number provided
socket = new Socket(server, port);
//Create new data input stream
dataIn = new DataInputStream(socket.getInputStream());
//Create new data outpit stream
dataOut = new DataOutputStream(socket.getOutputStream());
dataOut.writeUTF(name);
while (true)
{
gui.output.append("\n"+dataIn.readUTF());
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
//Send bid to output stream
public void sentBid(String bid)
{
try
{
//Write bid out
dataOut.writeUTF(bid);
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void disconnect()
{
try
{
socket.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Your AuctionClientMain class seems to be in the default package. The AuctionClient class is in package Auction. The .class file for AuctionClient needs to be in a subdirectory named Auction relative to AuctionClientMain.
Alternatively, put AuctionClient in the default package or put AuctionClientMain in package Auction.
On a side note, Java conventions are that package names are all lower case. It would be better to use package auction; instead of package Auction;.
Because AuctionClient is in the Auction pacakge, the compiler expects to find the Java source file in a directroy called Auction.

Categories

Resources