Multi-threading client/server, Socket Exception - java

Should be a simple fix that i am not able to correct. I am returning a total calculation, price * quantity, between the server and the client. However, I am receiving a java.net.SocketException: Connection Reset. I have inserted a ComputerServer class w/class HandleAClient, ComputerClient class and Computer class. I welcome any help. Thank you!
import java.io.*;
import java.util.*;
import java.net.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
public class ComputerServer
{
public static void main(String args[])
{
ServerSocket serverSocket;
Socket connection;
ObjectInputStream input;
ObjectOutputStream output;
Computer c = null;
Object obj;
double totalCharge;
try
{
serverSocket = new ServerSocket(8000);
System.out.println("Waiting for Client");
int clientNo = 1;
ExecutorService threadExecutor = Executors.newCachedThreadPool();
while(true)//runs indefinitely
{
connection = serverSocket.accept();
input = new ObjectInputStream(connection.getInputStream());
output = new ObjectOutputStream(connection.getOutputStream());
obj = input.readObject();
System.out.println("Object Received from client:\n"+obj);
if(obj instanceof Computer)
{
totalCharge = ((Computer)obj).getPrice()*((Computer)obj).getQuantity();
HandleAClient thread = new HandleAClient(connection, clientNo, totalCharge);
threadExecutor.execute(thread);
output.writeObject(totalCharge);
output.flush();
}
clientNo++;
}
}
catch(ClassNotFoundException cnfe)
{
cnfe.printStackTrace();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}//end of main
}
class HandleAClient implements Runnable
{
//**SHOULD i do object...
//Scanner input;
//Formatter output;
Object obj;
ObjectOutputStream output;
ObjectInputStream input;
Socket connection;
ServerSocket serverSocket;
int clientNo;
//variables for calculation
//variables for calculation
double price;
double totalCharge;
public HandleAClient(Socket connection, int clientNo, double totalCharge)
{
this.connection = connection;
this.clientNo = clientNo;
this.totalCharge = totalCharge;
}
public void run()
{
//ArrayList<Computer> cList = new ArrayList<Computer>();
try
{
input = new ObjectInputStream(connection.getInputStream());
output = new ObjectOutputStream(connection.getOutputStream());
/*while(input.hasNext())
{
//variable = input.next....
//print out calculation
price = input.nextDouble();
System.out.println("Price received from client:\t"+clientNo+"is"+price);
//DO CALCULATION, STORE IT
for(Computer c: cList)//**TRYING a for loop
{
totalCharge = ((Computer)c).getPrice() * ((Computer)c).getQuantity();
output.format("%.2f\n", totalCharge);
//output.flush();
}
//}*/
System.out.println("TotalCharge"+totalCharge);
System.out.println("Thread"+"\t"+clientNo+"\t"+"ended");
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
import java.util.*;
import java.io.*;
import java.net.*;
public class ComputerClient
{
public static void main(String args[])
{
Socket connection;
ObjectOutputStream output;
ObjectInputStream input;
Object obj;
Computer c = new Computer("Asus",1189.99,4);
try
{
connection = new Socket("localhost",8000);
output = new ObjectOutputStream(connection.getOutputStream());
input = new ObjectInputStream(connection.getInputStream());
output.writeObject(c);
output.flush();
//read back:
obj=(Object)input.readObject();
System.out.println(obj.toString());
}
catch(ClassNotFoundException cnfe)
{
cnfe.printStackTrace();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
import java.io.Serializable;
public class Computer implements Serializable
{
private String brand;
private double price;
private int quantity;
public Computer()
{
setBrand("");
setPrice(0.0);
setQuantity(0);
}
public Computer(String b, double p, int q)
{
setBrand(b);
setPrice(p);
setQuantity(q);
}
public String getBrand()
{
return brand;
}
public double getPrice()
{
return price;
}
public int getQuantity()
{
return quantity;
}
public void setBrand(String b)
{
brand = b;
}
public void setPrice(double p)
{
price = p;
}
public void setQuantity(int q)
{
quantity = q;
}
public String toString()
{
return("Brand: "+brand+"\t"+"Price: "+price+"\t"+"Quantity: "+quantity);
}
}

'Connection reset' usually means you have written to a connection that had already been closed by the peer. In other words, an application protocol error. You've written something that the peer didn't read. The next I/O operation, or a subsequent one depending on buffering, will get 'connection reset'.
In this case the server is writing totalCharge and initializing two ObjectOutputStreams, which both write headers to the stream. The client is only creating one ObjectInputStream, which reads one header, and reads one object, then closes the connection. So the other header is written nowhere and causes the exception.
You can't do this. You can't use multiple ObjectOutputStreams on the same socket, at least not without special care that isn't evident here. You also shouldn't be doing any I/O whatsoever in the accept loop. Move all the client processing to the HandleAClient class, which is what it's for after all, and don't do anything in the accept loop except accept connections and start threads for them.
Also neither your server nor your client is closing the connection. The server is just leaking sockets, and the client is just exiting. The operating system is closing it for you in the client case, but it's poor practice. Close your connections. In this case you should close the ObjectOutputStream.

Related

How to handle multiple streams from a lobby server to clients

So, I'm having an issue with a project of mine. I'm writing a multiplayer lobby system which will enable multiple users to join a lobby, readying themselves by pressing a key. The issue that I'm facing is when two players is readying themselves, the lobby is only printing out a message for the last player who readied themselves. The system is built up in the following way.
Main Server
package master;
import java.net.*;
import java.io.*;
import java.util.*;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import main.Lobby;
public class MainServer {
public static final int PORT = 4444;
public static final String HOST = "localhost";
public ArrayList<Lobby> serverList = new ArrayList<>();
public static void main(String[] args) throws IOException, ClassNotFoundException {
new MainServer().runServer();
}
public void runServer() throws IOException, ClassNotFoundException {
// Creating the server
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Main Server initiated.");
while (true) {
Socket socket = serverSocket.accept();
try {
// Establishing the connection to the Lobby server and then adding it to its list
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
objectOutputStream.writeObject("Server created successfully.");
Lobby s = (Lobby) objectInputStream.readObject();
this.serverList.add(s);
System.out.println("Server \"" + s.name + "\" added to game list.");
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
The lobby
package main;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.Semaphore;
import master.MainServer;
/**
* The Class Server.
*/
public class Lobby implements Serializable {
private static final long serialVersionUID = -21654L;
public static final int PORT = 4445;
public static final int MAX_USERS = 5000;
public static final String HOST = "localhost";
public String name = "Lobby Server";
public int clientNumber;
public int playerNumberReady = 0;
public boolean allPlayersReady = false;
public boolean OddurIsNice = false;
public static void main(String[] args) throws IOException, ClassNotFoundException {
Lobby s = new Lobby();
s.runServer();
}
public void runServer() throws IOException, ClassNotFoundException {
registerServer();
new Thread( () -> {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server waiting for connections...");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("User 1 is now connected");
clientNumber++;
new ObjectOutputStream(socket.getOutputStream()).writeObject("You are connected man");
Socket socket2 = serverSocket.accept();
System.out.println("User 2 is now connected");
clientNumber++;
// ObjectOutputStream objectOutputStream2 = new ObjectOutputStream(socket2.getOutputStream());
// objectOutputStream2.writeObject("You are player number " + clientNumber + ". Waiting for other players to join");
new ServerThread(socket, socket2).start();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}).start();
}
private void registerServer() throws UnknownHostException, IOException, ClassNotFoundException {
// Method for establishing a connection to the MainServer
Socket socket = new Socket(MainServer.HOST, MainServer.PORT);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
objectOutputStream.writeObject(this);
System.out.println((String) objectInputStream.readObject());
}
public class ServerThread extends Thread {
public Socket socket = null;
public Socket socket2 = null;
ServerThread(Socket socket, Socket socket2) {
this.socket = socket;
this.socket2 = socket2;
}
public void run() {
try {
// This method is for when the client want's to connect to the lobby
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
System.out.println("User 1 is now connected");
ObjectInputStream objectInputStream2 = new ObjectInputStream(socket2.getInputStream());
ObjectOutputStream objectOutputStream2 = new ObjectOutputStream(socket2.getOutputStream());
System.out.println("User 2 is now connected");
BoardGameClient joined = (BoardGameClient) objectInputStream.readObject();
System.out.println(joined.name + " is now connected.");
while(true) {
objectOutputStream.writeObject("You joined the server.");
objectOutputStream.writeObject("You are player Number " + 1);
objectOutputStream.writeObject("Press '1' if you are ready");
objectOutputStream2.writeObject("You joined the server.");
objectOutputStream2.writeObject("You are player Number " + 2);
objectOutputStream2.writeObject("Press '1' if you are ready");
if(objectInputStream.readObject().equals(1)) {
playerNumberReady++;
}
if(objectInputStream2.readObject().equals(1)) {
playerNumberReady++;
}
if(playerNumberReady != 2) {
allPlayersReady = false;
} else {
allPlayersReady = true;
}
if (allPlayersReady == false) {
objectOutputStream.writeObject("Waiting...");
objectOutputStream2.writeObject("Waiting...");
}
if (allPlayersReady == true) {
objectOutputStream.writeObject("Lets GO");
objectOutputStream2.writeObject("Lets GO");
}
while (true) {
System.out.println(objectInputStream.readObject());
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And the client
package main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.concurrent.Semaphore;
import master.MainServer;
public class BoardGameClient implements Serializable {
private int playerName;
private static final long serialVersionUID = -6224L;
public String name = "User";
private transient Socket socket;
public transient Scanner input = new Scanner(System.in);
public static void main(String[] args) {
BoardGameClient c = new BoardGameClient();
if (args.length > 0) {
c.name = args[0];
}
try {
c.joinServer();
} catch (ClassNotFoundException | IOException e) {
System.out.println("Failed to join server.");
e.printStackTrace();
}
}
public void joinServer() throws UnknownHostException, IOException, ClassNotFoundException {
socket = new Socket(Lobby.HOST, Lobby.PORT);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
while(true) {
objectOutputStream.writeObject(this);
BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in));
System.out.println(objectInputStream.readObject());
System.out.println(objectInputStream.readObject());
System.out.println(objectInputStream.readObject());
int ready = input.nextInt();
objectOutputStream.writeObject(ready);
System.out.println(objectInputStream.readObject());
objectOutputStream.writeObject(name + ": " + inputReader.readLine());
}
}
}
I sincerely hope, that someone will be able to help me out <3
Firstly, there's a few things that bug me about this code. Not to sound condescending but you need to avoid rewriting code as much as possible. What happens if you want 3 or more players in the future? Currently you'd have to manually create a whole socket eg socket3, and then rewrite all the code you've already written. This is bad. You've manually spent the time creating 2 sockets and then created 2 streams for both of these sockets etc etc.
This can be automated don't you think?
Secondly, you have a lot of public variables. Unless they are static and final, for the most part you should keep variables as private.
I've tinkered with your lobby class as seen below, which is more scalable. It's not perfect by any means, but I feel illustrates the direction of improvement you should be heading for. Look up SOLID OOP principles, they'll help you guaranteed.
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* The Class Server.
*/
public class Lobby implements Serializable {
private static final long serialVersionUID = -21654L;
public static final int PORT = 4445;
public static final int MAX_USERS = 5000;
public static final String HOST = "localhost";
private static final int MIN_USERS = 2;
private String name = "Lobby Server";
private int clientNumber;
private boolean gameRunning = false;
// set of client connections
private final Set<ServerThread> clientConnectionThreads = new LinkedHashSet<>();
public static void main(String[] args) throws IOException, ClassNotFoundException {
Lobby s = new Lobby();
s.createLobby();
}
public void createLobby() throws IOException, ClassNotFoundException {
// waits for all players to ready up in a different thread
new Thread(this::waitReady).start();
registerServer();
// Listens for clients
runServer();
}
public void runServer() {
// closes serverSocket automatically in this way
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Server waiting for connections...");
long ids = 0;
while (!gameRunning) {
// accepts a new client connection
Socket socket = serverSocket.accept();
if (clientConnectionThreads.size() >= MAX_USERS) {
// tell user server is full and dont add the connection
} else {
// calculates the new id of the incoming player and adds them to the lobby
ids++;
this.clientConnectionThreads.add(new ServerThread(ids, socket));
System.out.println("User " + ids + " is now connected");
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
/*
* loops until every player is ready and there is enough players and then starts
* the game.
*/
public void waitReady() {
while (true) {
try {
if (areAllReady() && this.clientConnectionThreads.size() >= MIN_USERS) {
startGame();
return;
}
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// returns true if all users are ready
public boolean areAllReady() {
return clientConnectionThreads.stream().allMatch(ServerThread::isReady);
}
public void startGame() {
System.out.println("Starting game...");
this.gameRunning = true;
clientConnectionThreads.forEach(ServerThread::startGame);
// do game stuff
}
// i havent touched this function
private void registerServer() throws UnknownHostException, IOException, ClassNotFoundException {
// Method for establishing a connection to the MainServer
Socket socket = new Socket(MainServer.HOST, MainServer.PORT);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
objectOutputStream.writeObject(this);
System.out.println((String) objectInputStream.readObject());
}
public class ServerThread extends Thread {
private final Socket socket;
private final ObjectInputStream in;
private final ObjectOutputStream out;
private final long id;
boolean ready = false;
private ServerThread(long id, Socket socket) throws IOException {
// does some basic initialization
this.socket = socket;
this.id = id;
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());
// starts this connection thread
this.start();
}
public boolean isReady() {
return ready;
}
public void run() {
try {
// sets up the client and waits for their input
BoardGameClient joined = (BoardGameClient) in.readObject();
System.out.println(joined.name + " is now connected.");
out.writeObject("You joined the server.");
out.writeObject("You are player Number " + id);
out.writeObject("Press '1' if you are ready");
out.flush();
// waits for user to return ready
while (!ready) {
try {
int input = in.readInt();
System.out.println("input: " + input);
ready = input == 1;
} catch (ClassCastException e) {
e.printStackTrace();
}
}
out.writeObject("Waiting for players...");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void startGame() {
// send client message etc etc
}
}
public String getName() {
return name;
}
}
I basically didn't change any of the other classes, except a few lines within the client class to make this work. (I've changed the ready input type from writeObject() to writeInt())
I haven't tested this for problems, but I know it works at least on a basic level.
I also suggest using writeUTS()/readUTS() instead of writeObject()/readObject() for sending and receiving Strings across streams as this will add extra complexity to the code.

readObject() hangs program

I just started learning about Serialization and tried to implement it. I have a server, a client and a student class. The server creates an initial instance of my student class. The client then connects to the server and tampers with the attributes associated with the student , i.e. bumps up the GPA.
For some reason my code does not get the point when I try to readObject() in the client class. Can't figure out why. Again, I'm very new to this topic so if I'm misunderstanding something major or minor about it please point it out. Any help is appreciated.
Here are my classes:
SERVER CLASS:
import java.io.*;
import java.net.*;
public class Server
{
Student s1 = null;
ServerSocket sock;
ListeningThread thread;
public Server(int port) throws IOException {
sock = new ServerSocket(port);
} // end of constructor
// starts the listening thread
public void start() {
thread = new ListeningThread();
thread.start();
} // end of start method
// stops the listening thread
public void shutdown() throws IOException {
thread.shutdown();
} // end of start method
private class ListeningThread extends Thread
{
Student s1 = new Student(0.5, "ABCDEFG", "Computer Science and Pure Math");
boolean keep_going;
public ListeningThread() {
super("The thread that listens");
}
public void shutdown() throws IOException
{
keep_going = false;
System.out.println("closing server socket");
sock.close();
System.out.println("Waiting for listening thread to exit");
try { join(); }
catch(InterruptedException e) {}
System.out.println("Server shut down");
}
public void run()
{
// Show student info before connecting to client
System.out.println("Student Name is : " + s1.getStudentName());
System.out.println("Student Major is : " + s1.getStudentMajor());
System.out.println("Student GPA is : "+ s1.getStudentGPA());
try
{
boolean keep_going = true;
while(keep_going)
{
System.out.println("Listening for connection on port "+
sock.getLocalPort());
Socket s = sock.accept();
ClientHandler handler = new ClientHandler(s);
handler.start();
System.out.println("Got a connection");
}
} catch(Exception e) {
e.printStackTrace();
}
} // end of run method
} // end of ListeningThread class
private class ClientHandler extends Thread
{
ObjectOutputStream serverOutputStream = null;
ObjectInputStream serverInputStream = null;
Socket socket;
/*************************************************************************
* #param socket The Socket object returned by calling accept() on the
* ServerSocket.
*************************************************************************/
public ClientHandler(Socket socket) throws Exception {
this.socket = socket;
} // end of constructor
public void run()
{
try
{
serverInputStream = new ObjectInputStream(socket.getInputStream());
serverOutputStream = new ObjectOutputStream(socket.getOutputStream());
s1 = (Student)serverInputStream.readObject();
System.out.println("DATA HAS BEEN TAMPERED");
serverOutputStream.writeObject(s1);
serverOutputStream.flush();
// Show student info after connecting to client, once we tampered with it
System.out.println("Student Name is : " + s1.getStudentName());
System.out.println("Student Major is : " + s1.getStudentMajor());
System.out.println("Student GPA is : "+ s1.getStudentGPA());
serverInputStream.close();
}catch(Exception e){e.printStackTrace();}
} // end of run method
} // end of ClientHandler inner class
}
CLIENT CLASS:
import java.io.*;
import java.net.*;
public class Main
{
public static void main(String[] arg) throws Exception
{
Student s1 = null;
Socket socketConnection = new Socket("127.0.0.1", 9876);
ObjectInputStream clientInputStream = new
ObjectInputStream(socketConnection.getInputStream());
ObjectOutputStream clientOutputStream = new
ObjectOutputStream(socketConnection.getOutputStream());
//System.out.println("I'VE TAMPERED WITH DATA");
//clientOutputStream.writeObject(s1);
/*****************************************************************
* Funny thing here that stomped me for quite a while is that
* .readObject() and .writeObject() exceptions aren't handled by
* IOException, which makes sense. And I was trying to catch an
* IOException for about 2 hours till I realized that.
*****************************************************************/
s1 = (Student)clientInputStream.readObject();
s1.setStudentGPA(4.00); // <<<---- hehe
clientOutputStream.writeObject(s1);
clientOutputStream.flush();
System.out.println("I'VE TAMPERED WITH DATA 1");
clientInputStream.close();
clientOutputStream.close();
System.out.println("I'VE TAMPERED WITH DATA 1");
}
}
AND MY STUDENT OBJECT CLASS:
import java.io.*;
import java.util.*;
public class Student implements Serializable
{
private String studentName, studentMajor;
private double studentGPA;
Student(double gpa, String name, String major)
{
studentName = name;
studentMajor= major;
studentGPA = gpa;
}
//-------------------------------------------------------
public String getStudentName()
{
return studentName ;
}
public String getStudentMajor()
{
return studentMajor ;
}
public double getStudentGPA()
{
return studentGPA ;
}
//-------------------------------------------------------
public void setStudentGPA(double gpa)
{
studentGPA = gpa;
}
}
EDIT:
I looked through your code and found that you have read the object first and tried to write it next in both client and the server.
Both client and server should not be reading at first because both of them will be waiting for data.
Either change the order of read and write, or implement read and write in separate threads.
Old answer:
The method readObject() is supposed to block the current thread, i.e., It will not proceed until some data is received.
The solution would be to implement your network related code in a separate background thread also in the client.

Sending messages to clients TCP connection fails with an nullpointexception [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Hi all :) Sorry for this really long question but this needs some explaination.
I was given an assignment where i have to turn a very simple game into a 2 player multiplayer game. The reason why we have to make this game is to learn more about threads and concurrency. I have never worked with concurrency nor with multiple threads.
My idea is to create a TCP server like i have done in GameServer.java where i create a new ServiceObject for each player. I create a thread for each ServiceObject where i will recieve, handle and send commands from a client.
Gameserver.java
package server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class GameServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(6789);
System.out.println("Waiting for clients to connect . . . ");
Socket s1 = server.accept();
System.out.println("Clients connected.");
PlayerService servicep1 = new PlayerService(s1);
Thread t1 = new Thread(servicep1);
Socket s2 = server.accept();
System.out.println("Clients connected.");
PlayerService servicep2 = new PlayerService(s2);
Thread t2 = new Thread(servicep2);
t1.start();
t2.start();
servicep1.sendDataToClient("ready");
servicep2.sendDataToClient("ready");
}
}
PlayerService.java
package server;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.LinkedBlockingQueue;
import game2016.Player;
public class PlayerService extends Thread {
private Socket s;
private PlayerService opponent;
private Scanner in;
private PrintWriter out;
public PlayerService(Socket aSocket) {
this.s = aSocket;
}
public void setOpponent(PlayerService opponent) {
this.opponent = opponent;
}
public void run() {
try {
in = new Scanner(s.getInputStream());
out = new PrintWriter(s.getOutputStream());
try {
doService();
} finally {
// s.close();
}
} catch (IOException exception) {
exception.printStackTrace();
}
}
public void doService() throws IOException {
while (true) {
if (!in.hasNext()) {
return;
}
String command = in.next();
if (command.equals("QUIT")) {
return;
} else
recieveFromClient(command);
}
}
public void recieveFromClient(String command) throws IOException {
System.out.println(command);
if(command.equals("player")) {
String newPlayerName = in.next();
int xPos = in.nextInt();
int yPos = in.nextInt();
String direction = in.next();
// sendDataToOpponent("addOpponent " + newPlayerName + " " + xPos + " " + yPos + " " + direction);
}
}
public void sendDataToClient(String response) {
out.write(response + "\n");
out.flush();
}
public void sendDataToOpponent(String response) {
opponent.sendDataToClient(response);
}
}
To send data from one client to another client i have a reference to the opponents servicelayer as i can invoke the sendDataToOpponent() method to send data to him and if the server have to communicate i can just invoke sendDataToClient() from the server.
My problem is that i want to postpone opening my clients GUI to both clients have connected.
Main.java(Client) - GUI code have been left out
private static Socket s;
private static InputStream instream;
private static OutputStream outstream;
private static Scanner in;
private static PrintWriter out;
private static boolean isOpponentConnected;
public static void main(String[] args) throws Exception {
openConnection();
reciever();
waitOpponentConected();
launch(args);
}
public static void waitOpponentConected() throws Exception {
while(!isOpponentConnected) {
System.out.println("Waiting for opponent");
Thread.sleep(2000);
}
System.out.println("Opponent is ready now");
}
public static void openConnection() throws IOException {
s = new Socket("localhost", 6789);
System.out.println("Connection established");
instream = s.getInputStream();
outstream = s.getOutputStream();
in = new Scanner(instream);
out = new PrintWriter(outstream);
}
public static void responseFromServer() throws IOException {
try {
while(in.hasNext()) {
String response = in.next();
if(response.equals("ready")) {
isOpponentConnected = true;
System.out.println("Ready");
}
}
} catch (Exception e) {
}
}
public static void reciever() {
Task<Void> task = new Task<Void>() {
#Override
protected Void call() throws Exception {
while(true) {
responseFromServer();
}
}
};
new Thread(task).start();
}
public static void sendCommandToServer(String command) throws IOException {
out.print(command + "\n");
out.flush();
}
I've created a Thread to recieve commands from the server, and when both clients have connected to the server it sends a string 'ready' to each of the clients. My thought was that The Main-thread sleeps till isOpponentConnected is true.
But my gameserver fails and prints out a nullpointer exception when the second clients connects to the server. I've spend to days reading and trying to fix this bug. When i run the code in debug mode, both clients recieves the ready signal and the GUI starts for both clients.
Exception in thread "main" java.lang.NullPointerException
at server.PlayerService.sendDataToClient(PlayerService.java:67)
at server.GameServer.main(GameServer.java:23)
Can you guys see anything i'm obviously doing wrong?
I think this queston is interesseting because it's not just the nullpointerexception, it's about structering TCP server-client relationships and the chain when things are initialized and ready when threads and connections are made.
It should be fixable from inside the PlayerService.java class you have posted.
I suggest moving:
in = new Scanner(s.getInputStream());
out = new PrintWriter(s.getOutputStream());
from public void run() to your PlayerService constructor:public PlayerService(Socket aSocket)
It looks like the function sendDataToClient is trying to use the out variable before it gets initialised.

Second thread quits instead of looping forward

This program uses a client to send a Computer object (attributes brand, price, quantity) and the server returns the total charge back to the client. It must be able to continuously run a loop that sends forward threads to a server.
However, after the second thread should be completed, the program stops. I need to figure out how to keep it running, Thank you. Classes attached are Computer, ComputerServer w/ HandleAClient, and ComputerClient. I apologize for the editing, i am still learning how to use this.
import java.io.Serializable;
public class Computer implements Serializable
{
private String brand;
private double price;
private int quantity;
public Computer()
{
setBrand("");
setPrice(0.0);
setQuantity(0);
}
public Computer(String b, double p, int q)
{
setBrand(b);
setPrice(p);
setQuantity(q);
}
public String getBrand()
{
return brand;
}
public double getPrice()
{
return price;
}
public int getQuantity()
{
return quantity;
}
public void setBrand(String b)
{
brand = b;
}
public void setPrice(double p)
{
price = p;
}
public void setQuantity(int q)
{
quantity = q;
}
public String toString()
{
return("Brand: "+brand+"\t"+"Price: "+price+"\t"+"Quantity: "+quantity);
}
}
import java.util.*;
import java.io.*;
import java.net.*;
public class ComputerClient
{
public static void main(String args[])
{
Socket connection;
Scanner scanner = new Scanner(System.in);
Scanner quantity = new Scanner(System.in);
Scanner price = new Scanner(System.in);
Scanner brand = new Scanner(System.in);
ObjectOutputStream output;
ObjectInputStream input;
String b;
double p;
int q;
Object obj;
try
{
int exit= 1;
connection = new Socket("localhost",8000);
output = new ObjectOutputStream(connection.getOutputStream());
input = new ObjectInputStream(connection.getInputStream());
while(exit!=-1)
{
System.out.println("Please Enter a Computer Brand\n");
b = brand.nextLine();
System.out.println("Please Enter the Price\n");
p = price.nextDouble();
System.out.println("Please Enter the Quantity\n");
q = quantity.nextInt();
Computer c = new Computer(b,p,q);
output.writeObject(c);
output.flush();
//read back:
obj=(Object)input.readObject();
System.out.println(obj.toString());
System.out.println("Press any Integer to Continue, To Exit Press -1");
exit = scanner.nextInt();
}
}
catch(ClassNotFoundException cnfe)
{
cnfe.printStackTrace();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
import java.io.*;
import java.util.*;
import java.net.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
public class ComputerServer
{
public static void main(String args[])
{
ServerSocket serverSocket;
Socket connection;
ObjectInputStream input;
ObjectOutputStream output;
Computer c = null;
Object obj;
double totalCharge;
try
{
serverSocket = new ServerSocket(8000);
System.out.println("Waiting for Client");
int clientNo = 1;
ExecutorService threadExecutor = Executors.newCachedThreadPool();
while(true)//runs indefinitely
{
connection = serverSocket.accept();
input = new ObjectInputStream(connection.getInputStream());
output = new ObjectOutputStream(connection.getOutputStream());
obj = input.readObject();
System.out.println("\nObject Received from Client:\n"+obj);
if(obj instanceof Computer)
{
totalCharge = ((Computer)obj).getPrice()*((Computer)obj).getQuantity();
HandleAClient thread = new HandleAClient(connection, clientNo, totalCharge);
threadExecutor.execute(thread);
output.writeObject(totalCharge);
output.flush();
}
clientNo++;
}
}
catch(ClassNotFoundException cnfe)
{
cnfe.printStackTrace();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}//end of main
}
class HandleAClient implements Runnable
{
//**SHOULD i do object...
//Scanner input;
//Formatter output;
Object obj;
ObjectOutputStream output;
ObjectInputStream input;
Socket connection;
ServerSocket serverSocket;
int clientNo;
//variables for calculation
//variables for calculation
double price;
double totalCharge;
public HandleAClient(Socket connection, int clientNo, double totalCharge)
{
this.connection = connection;
this.clientNo = clientNo;
this.totalCharge = totalCharge;
}
public void run()
{
//ArrayList<Computer> cList = new ArrayList<Computer>();
//connection = serverSocket.accept();
/*while(input.hasNext())
{
//variable = input.next....
//print out calculation
price = input.nextDouble();
System.out.println("Price received from client:\t"+clientNo+"is"+price);
//DO CALCULATION, STORE IT
for(Computer c: cList)//**TRYING a for loop
{
totalCharge = ((Computer)c).getPrice() * ((Computer)c).getQuantity();
output.format("%.2f\n", totalCharge);
//output.flush();
}
//}*/
System.out.println("\nTotal Charge\t"+totalCharge);
System.out.println("\nThread"+"\t"+clientNo+"\t"+"ended");
}
}
You messed up in a Server:
You are receiving object in a main thread, than you make a new thread that does nothing. So you receive information from the socket only once.
Another connection was obtained without a problem, but the old connection information was lost. The client was writing to its socket but you didn't do anything with it, because you've lost a reference to the stream.
I suppose you thought that new object comes to the server as a new socket, which was wrong.
try using this code for a Server:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class ComputerServer
{
public static void main(String args[]) throws IOException
{
ServerSocket serverSocket;
Socket connection;
serverSocket = new ServerSocket(8000);
int clientNo = 1;
ExecutorService threadExecutor = Executors.newCachedThreadPool();
while (true)// runs indefinitely
{
System.out.println("Waiting for client");
connection = serverSocket.accept();
System.out.println("Client connected: " + connection.getPort());
HandleAClient thread = new HandleAClient(connection, clientNo);
threadExecutor.execute(thread);
clientNo++;
}
}
}
class HandleAClient implements Runnable
{
ObjectOutputStream output;
ObjectInputStream input;
ServerSocket serverSocket;
int clientNo;
public HandleAClient(Socket connection, int clientNo)
{
this.clientNo = clientNo;
try
{
this.input = new ObjectInputStream(connection.getInputStream());
this.output = new ObjectOutputStream(connection.getOutputStream());
} catch (IOException e)
{
e.printStackTrace();
}
}
#Override
public void run()
{
while (true)
{
try
{
Object obj = input.readObject();
System.out.println("\nObject Received from Client:\n" + obj);
if (obj instanceof Computer)
{
Computer c = (Computer) obj;
double totalCharge = c.price * c.quantity;
System.out.format("\nTotal Charge[%d]\t%f", clientNo,
totalCharge);
output.writeObject(totalCharge);
output.flush();
}
} catch (Exception e) { //JUST FOR BREVITY
e.printStackTrace();
}
}
}
}

Stuck with Multi-Client Chat Application

I'm trying to make a MultiClient Chat Application in which the chat is implemented in the client window. I've tried server and client code for the same. I've got two problems:
A. I believe the code should work but, server to client connections are just fine but information isn't transferred between clients.
B. I need a way to implement private one-to-one chat in case of more than two clients, I've used a class to store the information of the Socket object returned for each connection being established, but I can't figure out how to implement it.
The server code is:
import java.io.*;
import java.net.*;
class ClientInfo {
Socket socket;
String name;
public ClientInfo(Socket socket, String name) {
this.socket = socket;
this.name = name;
}
}
public class server {
private ObjectInputStream input[] = null;
private ObjectOutputStream output[] = null;
private String value = null;
private static ServerSocket server;
private Socket connection = null;
private static int i = -1;
public static void main(String args[]) {
try {
server = new ServerSocket(1500, 100);
while (true) {
System.out.println("Waiting for connection from client");
Socket connection = server.accept();
i++;
System.out.println("Connection received from " + (i + 1) + " source(s)");
//System.out.println(i);
new ClientInfo(connection, "Client no:" + (i + 1));
innerChat inc = new server().new innerChat(connection);
}
} catch (Exception e) {
System.out.println("Error in public static void main! >>>" + e);
}
}// end of main!!!
class innerChat implements Runnable {
private Socket connection = null;
public innerChat(Socket connection) {
this.connection = connection;
Thread t;
t = new Thread(this);
t.start();
}
public void run() {
try {
output[i] = new ObjectOutputStream(connection.getOutputStream());
output[i].flush();
input[i] = new ObjectInputStream(connection.getInputStream());
} catch (Exception e) {
}
}
}
}
And the client code is
import java.net.*;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.*;
import java.awt.event.*;
public class ChatappClient {
private static int port = 1500;
JFrame window = new JFrame("Chat");
JButton sendBox = new JButton("Send");
JTextField inputMsg = new JTextField(35);
JTextArea outputMsg = new JTextArea(10, 35);
private ObjectInputStream input;
private ObjectOutputStream output;
public static void main(String[] args) throws Exception {
ChatappClient c = new ChatappClient();
c.window.setVisible(true);
c.window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c.run();
}
public ChatappClient() {
inputMsg.setSize(40, 20);
sendBox.setSize(5, 10);
outputMsg.setSize(35, 50);
inputMsg.setEditable(true);
outputMsg.setEditable(false);
window.getContentPane().add(inputMsg, "South");
window.getContentPane().add(outputMsg, "East");
window.getContentPane().add(sendBox, "West");
window.pack();
sendBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
output.writeObject(inputMsg.getText());
outputMsg.append("\n" + "Client>>>" + inputMsg.getText());
output.flush();
} catch (IOException ie) {
outputMsg.append("Error encountered! " + ie);
}
inputMsg.setText("");
}
});
inputMsg.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
output.writeObject(inputMsg.getText());
outputMsg.append("\n" + "Client>>>" + inputMsg.getText());
output.flush();
} catch (IOException ie) {
outputMsg.append("Error encountered! " + ie);
}
inputMsg.setText("");
}
});
}
private void run() throws IOException {
Socket clientSocket = new Socket("127.0.0.1", port);
output = new ObjectOutputStream(clientSocket.getOutputStream());
output.flush();
input = new ObjectInputStream(clientSocket.getInputStream());
outputMsg.append("I/O Success");
String value = null;
while (true) {
try {
value = (String) input.readObject();
} catch (Exception e) {
}
outputMsg.append(value + "\n");
}
}
}
Your code looks like it could be improved quite a bit. Your main method for instance should have none of that code in it. It should start your Server class, and that's it (and note that class names should begin with an upper case letter as per Java standards which I strongly advise you to follow).
I'm trying to make a MultiClient Chat Application in which a Server does nothing but listen and create connections.
The Server is going to have to do more than that. It will need to create Clients, it will need to maintain a collection such as an ArrayList of Clients such as an ArrayList<ChatappClient> Otherwise how do you expect the Server to connect two Clients together?
I think that in all you're going to need to think the structure and connections of this program out in more depth before starting to write code.

Categories

Resources