KnockKnockServer in Java - java

I am newbie in java networking ,I am trying to make a server application in java called instant messaging without GUI. So whenever i run the program it says
" Main method not found in class Methods, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application" -ECLIPSE
Please help me what's wrong in my code.
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
// FIRST FILE //
public class main{
public static void main (String[] args) {
Server s=new Server();
s.runningserver();
}
}
//SECOND FILE//
public class Server {
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
//wait For Connection,then display connection information
private void waitforConnection() {
System.out.println("wait for Someone to Connect.....\n");
try {
connection=server.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("error In Acceptance of Server!!\n...");
}
System.out.println(("Connection Established"+connection.getInetAddress().getHostName()));
}
//Setting Up Streams to Get Input and Output
private void setupStreams(){
try {
output=new ObjectOutputStream(connection.getOutputStream());
output.flush();
input=new ObjectInputStream(connection.getInputStream());
System.out.println("Your Streams are Perfectly Working...");
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("Error Found! in Streaming Connectionos");
e.printStackTrace();
}
}
// While Chatting Method....!!//
private void whileChatting() throws IOException{
String Message="You are now Connected!!\n";
sendMessage(Message);
//abletoType(true);
do{
try{
Message=(String) input.readObject();
System.out.println("\n"+Message);
}
catch(ClassNotFoundException e ){
System.out.println("wtf---Fuck\n YOu\n Bloody\n HAcker!!!\n");
}
}
while(!Message.equals("CLIENT--END"));
}
// Closing All Streams and Socket after you are done//
private void closeCrap(){
System.out.println("\nClosing Connection...........Bye Bye\n");
//abletoType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Couldn't Close Connections!");
}
}
//Sending Messages to Client
private void sendMessage(String message){
try {
output.writeObject("SERVER--- "+message);
output.flush();
System.out.println("\nServer- "+message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Dude I cant Send yeaah..");
}
}
// Setting up the Server
public void runningserver(){
try {
server=new ServerSocket(4444,100);
while(true){try{
//connect and Have connection
waitforConnection();
setupStreams();
whileChatting();
}
finally{
closeCrap();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

EDIT: Here is the solution and I checked it and for me it works (run the MainClass.java file!):
//MainClass.java file:
public class MainClass {
public static void main (String[] args) {
Server s=new Server();
s.runningserver();
}
}
//Server.java file:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
// wait For Connection,then display connection information
private void waitforConnection() {
System.out.println("wait for Someone to Connect.....\n");
try {
connection = server.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("error In Acceptance of Server!!\n...");
}
System.out.println(("Connection Established" + connection
.getInetAddress().getHostName()));
}
// Setting Up Streams to Get Input and Output
private void setupStreams() {
try {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
System.out.println("Your Streams are Perfectly Working...");
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("Error Found! in Streaming Connectionos");
e.printStackTrace();
}
}
// While Chatting Method....!!//
private void whileChatting() throws IOException {
String Message = "You are now Connected!!\n";
sendMessage(Message);
// abletoType(true);
do {
try {
Message = (String) input.readObject();
System.out.println("\n" + Message);
} catch (ClassNotFoundException e) {
System.out.println("wtf---Fuck\n YOu\n Bloody\n HAcker!!!\n");
}
} while (!Message.equals("CLIENT--END"));
}
// Closing All Streams and Socket after you are done//
private void closeCrap() {
System.out.println("\nClosing Connection...........Bye Bye\n");
// abletoType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Couldn't Close Connections!");
}
}
// Sending Messages to Client
private void sendMessage(String message) {
try {
output.writeObject("SERVER--- " + message);
output.flush();
System.out.println("\nServer- " + message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Dude I cant Send yeaah..");
}
}
// Setting up the Server
public void runningserver() {
try {
server = new ServerSocket(4444, 100);
while (true) {
try {
// connect and Have connection
waitforConnection();
setupStreams();
whileChatting();
} finally {
closeCrap();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I can run that without an exception.
The Problem is your main method
public static void main (String[] args) {}
Is not in the class where you run it.
//separate file A.java
public class A
{}
//separate file B.java
public class B
{
public static void main (String[] args) {}
}
If you now run B, it works, because B.java has a main method. BUT: if you run A.java it says:
no main methode found. The file you want to run (A, B, etc. must have a main method defined)
If you run a java file, it will look for a main method (start point of execution).

The main method must be a method of the class:
import java.net.Socket;
public class Server {
public static void main (String[] args) {
Server s=new Server();
s.runningserver();
}
So it must come after the class declaration.

Related

Threaded Server stuck on accept() AKA How to shutdown a MulThreaded Server via client input?

Since I am stuck for this for a week now and still haven't firgured it out I try to express what I want as cleary as possible.
I have a Server which can handle Multiple Clients and communicates with them.
Whenever a client connects, the server passes the Client's request to my class RequestHandler, in which the clients commands are being processed.
If one of the clients says "SHUTDOWN", the server is supposed to cut them loose and shut down.
It doesn't work.
If only one client connects to the server, the server seems to be stuck in the accept() call and I do not know how to fix this.
THERE is already one response, but please do not take note of it, it was on a different topic which is outdated
I have two approaches and both don't seem to work.
1)If the client writes "SHUTDOWN", the shutdownFlag is set to true (in hope to exit the while loop)
2)If the client writes "SHUTDOWN", the static method shutdown() is called on the Server, which should shut him down
Below you see the implementation of my Server class, the other two classes involved are Client(all he does is connect to the Socket) and RequestHandler (this class processes the Input and writes it) .
I am 98% sure the problem lies within the Server class.
Below this is an even shorter version of the Server with just the methods without any Console outputs which might help understanding it in case you want to copy the code
public class Server {
public static final int PORTNUMBER = 8540;
public static final int MAX_CLIENTS = 3;
public static boolean shutdownFlag = false;
public static ExecutorService executor = null;
public static ServerSocket serverSocket = null;
public static void main(String[] args) {
ExecutorService executor = null;
try (ServerSocket serverSocket = new ServerSocket(PORTNUMBER);) {
executor = Executors.newFixedThreadPool(MAX_CLIENTS);
System.out.println("Waiting for clients");
while (!shutdownFlag) {
System.out.println("shutdown flag ist : " + shutdownFlag);
Socket clientSocket = serverSocket.accept();
Runnable worker = new RequestHandler(clientSocket);
executor.execute(worker);
System.out.println("Hallo");
}
if (shutdownFlag) {
System.out.println("Flag is on");
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
//Stop accepting requests.
serverSocket.close();
} catch (IOException e) {
System.out.println("Error in server shutdown");
e.printStackTrace();
}
serverSocket.close();
}
System.out.println("shutting down");
} catch (IOException e) {
System.out
.println("Exception caught when trying to listen on port "
+ PORTNUMBER + " or listening for a connection");
System.out.println(e.getMessage());
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
public static void shutdown(){
if (shutdownFlag) {
System.out.println("Flag is on");
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
//Stop accepting requests.
serverSocket.close();
} catch (IOException e) {
System.out.println("Error in server shutdown");
e.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Server {
public static final int PORTNUMBER = 8540;
public static final int MAX_CLIENTS = 3;
public static boolean shutdownFlag = false;
public static ExecutorService executor = null;
public static ServerSocket serverSocket = null;
public static void main(String[] args) {
ExecutorService executor = null;
try (ServerSocket serverSocket = new ServerSocket(PORTNUMBER);) {
executor = Executors.newFixedThreadPool(MAX_CLIENTS);
while (!shutdownFlag) {
Socket clientSocket = serverSocket.accept();
Runnable worker = new RequestHandler(clientSocket);
executor.execute(worker);
}
if (shutdownFlag) {
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
serverSocket.close();
}
} catch (IOException e) {
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
public static void shutdown() {
if (shutdownFlag) {
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
If you move the code in main into an instance method on Server (we'll say run here) you can just do new Server().run() inside main. That way you have an instance (this) to work with inside your run method.
Something like this:
class Server {
private boolean shutdownFlag = false; // This can't be static anymore.
public static final Server SERVER = new Server();
public static void main(String[] args) {
SERVER.run();
}
private void run() {
// Here goes everything that used to be inside main...
// Now you have the Server.SERVER instance to use outside the class
// to shut things down or whatever ...
}
}
This pattern isn't actually that great but better would be too long for here. Hopefully this gets you off to a good start.

How to print message from a server to the textclient?

I want to print message from a server.For example:I am User1 and I am chatting with user User2.
I want to see this(in the text client console):
User1:Hello
User2:Hi!How are you?
I can see the messages I sent but only in the Server console.Here is my code(to show message in console in text client class):
EDIT:I have put all the classes that I modified.I didn't put the exceptions classes,ServerConfig and Message and PrivateMessage.ServerConfig return port 9000 and max clients 100,the method getAll() from message returns the message+sender.
import java.net.*;
import java.io.*;
public class ClientPeer extends Thread{
String _username;
Socket _Socket;
public ClientPeer(String _username, Socket _Socket)
{
this._username = _username;
this._Socket = _Socket;
}
public void run()
{
try{
ObjectInputStream _objin=new ObjectInputStream(_Socket.getInputStream());
Message _messfromserver=(Message)_objin.readObject();
System.out.println(_messfromserver.getAll());
}catch(IOException e){e.printStackTrace();}
catch(ClassNotFoundException e){e.printStackTrace();}
}
public void sendMessage(String _message) throws IOException {
ObjectOutputStream _obj = new ObjectOutputStream(
_Socket.getOutputStream());
_obj.writeObject(new Message(_username, _message));
_obj.flush();
}
public void sendMessage(String _message, String _receiver)
throws IOException {
ObjectOutputStream _obj = new ObjectOutputStream(
_Socket.getOutputStream());
_obj.writeObject(new PrivateMessage(_username, _message, _receiver));
_obj.flush();
}
}
Server :
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
static ServerConfig _svconfig = new ServerConfig();
// final static int _mysocket;
public static void main(String[] args) {
try {
final int _mysocket = _svconfig.getPORTNumber();
ServerSocket _serversocket = new ServerSocket(_mysocket);
Socket _clientsocket = _serversocket.accept();
ServerPeer _serverpeer = new ServerPeer(_clientsocket);
_serverpeer.methodCall();
_serversocket.close();
}
catch (MissingKeyException e) {
e.printStackTrace();
} catch (UnknownKeyException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (ConnectException e) {
e.printStackTrace();
} catch (BindException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (SocketException e) {
System.out.println("You have been disconnected");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
TextClient:
import java.io.*;
import java.net.*;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class TextClient {
public TextClient() {
}
public static void main(String[] args) throws IOException,
UnknownHostException, ConnectException,InterruptedException {
Socket _socket = new Socket("localhost", 9000);
System.out.println("Please enter your desired username:");
Scanner _new = new Scanner(System.in);
String _inputname = _new.nextLine();
System.out.println("Success.You can now type your messages!");
ClientPeer _clientpeer = new ClientPeer(_inputname, _socket);
Scanner _scan = new Scanner(System.in);
String _input = _scan.nextLine();
_clientpeer.start();
while (true) {
if (!_input.equals("exit")) {
if (_input.startsWith("/w"))
_clientpeer.sendMessage(_input, "username");
else
_clientpeer.sendMessage(_input);
} else
break;
_input = _scan.nextLine();
}
}
}
ServerPeer:
import java.net.*;
import java.io.*;
public class ServerPeer {
Socket _socket;
public ServerPeer(Socket _socket) {
this._socket = _socket;
}
public void methodCall() throws IOException, UnknownHostException,
ClassNotFoundException {
ObjectInputStream _ois = new ObjectInputStream(_socket.getInputStream());
Message _message;
while (_socket.isConnected()) {
_message = (Message) _ois.readObject();
System.out.print( _message.getAll());
_ois = new ObjectInputStream(_socket.getInputStream());
}
}
}
The question is really unspecified. If you want to see it on the client console just initiate the console on the client-side and print out the messages. Can you tell more about the problem? Where you need help?

Server reply to Client message failing due to closed socket - Java Client-Server example

I'm creating this little client-server program to learn about sockets, and so far, I'm having a bit of trouble. For the purpose of this post, I consolidated the code into a single class. And the code will compile. (So it will show the same errors I get)
When the client connects to the server, the server socket properly creates a socket on the server-side. The Client then successfully sends a message to the server, but when the server tries to send a response to the client, there is an error saying the socket is closed.
Main.java
package main;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Hashtable;
public class Main {
boolean running = true;
public static void main(String[] args){
new Main().start();
}
public void start(){
new Thread(new ConnectionListener()).start(); //Starts Server
try {
connectToServer();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public class ConnectionListener implements Runnable{
public void run() {
ServerSocket ss = null;
try {
ss = new ServerSocket(31415);
}catch (BindException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
while(running){
try {
Socket sock = ss.accept();
ServerConnection c = new ServerConnection(sock);
c.start();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void connectToServer() throws UnknownHostException, IOException{
//Create Connection to Server
Socket socket = new Socket("localhost",31415);
ClientConnection cc = new ClientConnection(socket);
cc.start();
//Send First Message to Server
Hashtable<Integer, String> htt = new Hashtable<Integer, String>();
htt.put(0,"Hello, This is a Chat Test");
Message m = new Message(Message.Type.CHAT,htt);
cc.sendMessage(m);
}
public class ServerConnection{
Socket sock;
boolean connected = true;
public ServerConnection(Socket sock){
this.sock = sock;
}
public void start() {
new Thread(new RequestListener()).start();
}
private void handleMessage(Message m){
System.out.println("Server : Handle message " + m.type.toString());
}
public void disconnect(){
System.out.println("Disconnect user");
}
public void sendMessage(Message m){
try {
ObjectOutputStream os = new ObjectOutputStream(sock.getOutputStream());
os.writeObject(m);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class RequestListener implements Runnable{
public void run() {
ObjectInputStream is = null;
try {
is = new ObjectInputStream(sock.getInputStream());
while(connected){
try {
Message m = (Message)
is.readObject(); //EOFException
handleMessage(m);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch(SocketException e){
disconnect();
e.printStackTrace();
break;
}catch (IOException e) {
//e.printStackTrace(); //EOFException Here
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class ClientConnection {
private Socket socket;
private boolean connected = true;
public ClientConnection(Socket socket) {
this.socket = socket;
}
public void start(){
new Thread(new RequestListener()).start();
}
public void sendMessage(Message m){
try {
ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
os.writeObject(m);
os.flush();
os.close();
} catch (IOException e) {
System.out.println("Error Sending Message");
e.printStackTrace();
}
}
public void close() throws IOException{
Message m = new Message(Message.Type.DISCONNECT,null);
sendMessage(m);
socket.close();
}
private void handleMessage(Message m){
System.out.println("Client : Handle message " + m.type.toString());
}
class RequestListener implements Runnable{
public void run() {
ObjectInputStream is = null;
try {
System.out.println(socket.isConnected()); //true
System.out.println(socket.isClosed()); //false
InputStream iss = socket.getInputStream();
is = new ObjectInputStream(iss); //socketClosedException
while(connected){
try {
Message m = (Message)is.readObject();
handleMessage(m);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch(SocketException e){
System.out.println("Server Disconnected");
break;
}catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
Message.java
package main;
import java.io.Serializable;
import java.util.Hashtable;
public class Message implements Serializable{
public enum Type{
LOGIN, PM, DISCONNECT, INCORRECT_LP,CORRECT_LP, UPDATE_USERLIST, CHAT, INCORRECT_VERSION
}
public Type type;
Hashtable ht;
public Message(Type type, Hashtable ht){
this.type = type;
this.ht = ht;
}
public Object get(Object o){
return ht.get(o);
}
}
There's nothing 'random' about it.
Closing the input or output stream of a Socket closes the other stream and the Socket.
In this case you are closing the ObjectOutputStream you have wrapped around the socket's output stream, which closes that output stream, which closes the socket's input stream and the socket.

ActiveMQ: How to get all messages in a queue for Receiver (Java)

Here is the Server's code:
import java.net.UnknownHostException;
import java.io.IOException;
import org.apache.activemq.transport.stomp.StompConnection;
public class Server{
public static void main(String[] args) {
try {
StompConnection con = new StompConnection();
con.open("localhost", 61618);
con.connect("admin", "admin123");
con.begin("a1");
con.send("/queue/test1", "This is test message 1");
con.send("/queue/test1", "This is test message 2");
con.send("/queue/test1", "This is test message 3");
con.commit("a1");
con.disconnect();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here is the Client's code:
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Scanner;
import org.apache.activemq.transport.stomp.StompConnection;
import org.apache.activemq.transport.stomp.StompFrame;
import org.apache.activemq.transport.stomp.Stomp.Headers.Subscribe;
public class Client {
public static void main(String[] args) {
try {
//login.
Scanner in = new Scanner(System.in);
System.out.print("Password: ");
String pass = in.next();
if (!"123".equals(pass)){
System.out.println("Sorry, wrong password.");
}
else
{
StompConnection con= new StompConnection();
con.open("localhost", 61618);
con.connect("admin", "admin123");
con.subscribe("/queue/test1", Subscribe.AckModeValues.CLIENT);
con.begin("a2");
StompFrame mes = con.receive();
System.out.println(mes.getBody());
con.ack(message, "a2");
con.commit("a2");
con.disconnect();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have 3 messages on Server. However, I only can get 1 message per time in Client. How to get all the messages in the queue in a run? Anyone can help me?
Not entirely sure what you've tried here but to read all three is just a simple loop like:
con.begin("a2");
while (true) {
StompFrame message = null;
try {
message = connection.receive(5000);
} catch (Exception e) {
break;
}
System.out.println(mes.getBody());
con.ack(message, "a2");
}
connection.commit("a2");

Accessing a public static arrayList of a Thread Class from another Thread's Class

I am trying to access the
public static List<ChatThread> Chat_list of my ChatThread Class
from the run() method of my Client Class but i keep getting an empty array(Infact it throws an exception at that point : Exception in thread "Thread-2" java.lang.NullPointerException)
and am very certain that that arrayList exists and is not empty(Because i did a test on the arrayList in my ChatThread Class). Just take a look at my code.
Please I need your help on what to do.
Thanks.
This is the class containing the arrayList :
public class ChatThread extends Thread {
private Socket sc;
private String cherry_name;
private String passwd;
public static List<ChatThread> Chat_list = new ArrayList<ChatThread>(); //THE STATIC ARRAY LIST
private BufferedReader br;
private BufferedWriter bw;
public ChatThread(Socket sc){
try {
this.sc=sc;
System.out.println(sc);
br = new BufferedReader(new InputStreamReader(sc.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(sc.getOutputStream()));
String help = br.readLine();
this.cherry_name=help.split("#")[0];
this.passwd=help.split("#")[1];
System.out.println(this.cherry_name);
System.out.println(this.passwd);
Chat_list.add(this); //This is where i add it to the arrayList
if(Chat_list.isEmpty()) //This is where i did the test
System.out.println("I am empty");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run(){
//Comparaison of information with that in the database
try{
bw.write("success");
bw.newLine();
bw.flush();
while(true){
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Socket getSc() {
return sc;
}
public String getCherry_name() {
return cherry_name;
}
}
As for the Client class :
public class Client extends Thread {
private Socket socket;
private BufferedReader br;
private BufferedWriter bw;
private ChatThread th;
private String cherry_name;
public Client(String cherry_name,String passwd){
try
{
socket = new Socket("127.0.0.1", 8888);
this.cherry_name=cherry_name;
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write(cherry_name+"#"+passwd);
bw.newLine();
bw.flush();
}
catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Erreur lors de la lecture du socket");
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
public void run()
{
try {
String help = br.readLine();
if(help.equals("failed")){
this.notify();
this.destroy();
socket.close();
}
else{
if(ChatThread.Chat_list.isEmpty()) System.out.println("Empty array!!!"); //This is where it says the array is empty whereas it wasn't the case in the ChatThread Class
for(ChatThread ct : ChatThread.Chat_list){
if(cherry_name.equals(ct.getCherry_name())){
th=ct;
break;
}
}
while(true){
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Error whilst reading from the socket");
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("Interruption");
e.printStackTrace();
}
}
public Socket getSocket() {
return socket;
}
}
And my server class :
public class Server {
public static void main(String[] args) {
try {
ServerSocket server =new ServerSocket(8888);
Socket sc;
System.out.println("Server Started");
while(true){
sc=server.accept();
System.out.println("New Connection");
new ChatThread(sc).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
A main class to instantiate the Client class :
public class help {
public static void main(String[] argv) {
new Client("Jerry","Smith").start();
}
}
Every access to a mutable object shared between two threads must be accessed in a synchronized way. Not synchronizing will lead to visibility and coherence issues like you're seeing.
You should not expose an ArrayList like that (even without multiple threads, public static mutable objects are already a very bad practice). Instead, you should encapsulate it in your own object, and make sure every access is synchronized properly.
It's hard to give a more concrete advice without seeing any line of your code.

Categories