javasocketsnullconnectionserversocket

Why is this socket null?


I am creating a multi client chat server and I am pretty confident that it will work (Correct me if I'm wrong).

I have the issue that on the socket that the client connects to is null, so the connections can't be created because I use if(Socket != null), so I don't get errors.

The server starts with a starter class called (LaunchServer) that uses the class object ClientConnector as Minecraft, and then starts the method runServer().

LaunchServer class:

public class LaunchServer
{
    public static void main(String[] args)
    {
        System.out.println("[Info] Running");
        ClientConnector Minecraft = new ClientConnector();
        Minecraft.runServer();
    }
}

ClientConnector class:

import java.util.ArrayList;
import java.net.*;
import java.io.*;

public class ClientConnector
{
    
    public static ArrayList<Socket> Connections = new ArrayList<Socket>();
    
    public static void runServer()
    {
        try
        {   
            System.out.println("[Info] Attempting to bind to port 1337.");
            @SuppressWarnings("resource")
            ServerSocket serversocket = new ServerSocket(1337);
            System.out.println("[Info] Bound to port 1337.");
            System.out.println("[Info] Waiting for client connections...");
            while(true)
            {
                Socket socket = serversocket.accept();
                new ClientHandler(socket).start();
                Connections.add(socket);
            }
            
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

Handler class:

import java.io.*;
import java.net.*;

public class ClientHandler extends Thread
{
    Socket Socket;

    public ClientHandler(Socket socket)
    {
        socket = Socket;
        System.out.println("[Info] Client connected on port 1337.");
    }
    
    public void run()
    {
        while(true)
        {
            for(int i = 0; i < ClientConnector.Connections.size(); i++)
            {
                
                try
                {
                    if(Socket != null)//This stays null...
                    {
                        ObjectOutputStream Output = new //These can't be created... 
                        ObjectOutputStream(Socket.getOutputStream());
                        ObjectInputStream Input = new ObjectInputStream(Socket.getInputStream());
                        whileChatting(Input, Output);
                    }
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
    
    public static void sendMessage(String message, String returnedMessage, ObjectOutputStream out)
    {
        try
        {
            
            if(!message.isEmpty())
            {
                out.writeObject("\247c[Server]\247d " + message);
                out.flush();
                System.out.println("[Chat] Sent: " + message);
            }
            else
            {
                out.writeObject(returnedMessage);
                System.out.println("[Chat] Sent: " + returnedMessage);
            }
            out.flush();
            System.out.println("[Info] Fluching remaining data to stream.");
            System.out.println("\n[Server] " + message);
        }
        catch(IOException ioException)
        {
            System.out.println("[Warning] Error: ioException @ sendMessage line 76.");
        }
     }
    
    public static void whileChatting(ObjectInputStream input, ObjectOutputStream output) throws IOException
    {
        String message = "";
        do
         {
             try
             {
                 message = (String) input.readObject();
                 System.out.println("\n" + message);
                 sendMessage("", message, output); 
             }
             catch(ClassNotFoundException classNotFoundException)
             {
                 System.out.println("[Warning] Error: ClassNotFoundException @ whileChatting line 1-7.");
                 System.out.println("\n idk wtf that user sent!");
             }
         }while(!message.equals("/stop"));
     }
}

The run method contains the null problem.

Would the connection get accepted, then passed to the handler class? How can a null connection get accepted?

How can I fix this problem?


Solution

  • The problem is you've got a logic error due to un-recommended naming conventions. You shouldn't name variables with keywords, like your Socket variable, and each variable should have a distinguishable name. e.g. not socket1, socket2 but serverSocket, clientSocket because that will make it easier for you and anyone else to read and fix your code.

    Change

    Socket Socket;
    

    to

    Socket connectedSocket;
    

    and in your constructor

    socket = Socket;
    

    to

    connectedSocket = socket;
    

    then finally, in your run() method change

    if(Socket != null)
    

    to

    if(connectedSocket != null)