Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7586279
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T19:23:18+00:00 2026-05-30T19:23:18+00:00

I’m trying to implement Java server and C client. I get java.lang.NullPointerException when I

  • 0

I’m trying to implement Java server and C client. I get java.lang.NullPointerException when I try to send string multiple times.

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

public class EchoServer
{        
    ServerSocket m_ServerSocket;


    public EchoServer() 
    {
        try
        {
            // Create the server socket.
            m_ServerSocket = new ServerSocket(12111);
        }
        catch(IOException ioe)
        {
            System.out.println("Could not create server socket at 12111. Quitting.");
            System.exit(-1);
        }

        System.out.println("Listening for clients on 12111...");

        // Successfully created Server Socket. Now wait for connections.
        int id = 0;
        while(true)
        {                        
            try
            {
                // Accept incoming connections.
                Socket clientSocket = m_ServerSocket.accept();

                // accept() will block until a client connects to the server.
                // If execution reaches this point, then it means that a client
                // socket has been accepted.

                // For each client, we will start a service thread to
                // service the client requests. This is to demonstrate a
                // multithreaded server, although not required for such a
                // trivial application. Starting a thread also lets our
                // EchoServer accept multiple connections simultaneously.

                // Start a service thread

                ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++);
                cliThread.start();
            }
            catch(IOException ioe)
            {
                System.out.println("Exception encountered on accept. Ignoring. Stack Trace :");
                ioe.printStackTrace();
            }
        }
    }

    public static void main (String[] args)
    {
        new EchoServer();    
    }


    class ClientServiceThread extends Thread
    {
        Socket m_clientSocket;        
        int m_clientID = -1;
        boolean m_bRunThread = true;

        ClientServiceThread(Socket s, int clientID)
        {
            m_clientSocket = s;
            m_clientID = clientID;
        }

        public void run()
        {            
            // Obtain the input stream and the output stream for the socket
            // A good practice is to encapsulate them with a BufferedReader
            // and a PrintWriter as shown below.
            BufferedReader in = null; 
            PrintWriter out = null;

            // Print out details of this connection
            System.out.println("Accepted Client : ID - " + m_clientID + " : Address - " + 
                             m_clientSocket.getInetAddress().getHostName());

            try
            {                                
                in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream()));
                out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream()));

                // At this point, we can read for input and reply with appropriate output.

                // Run in a loop until m_bRunThread is set to false
                while(m_bRunThread)
                {                    
                    // read incoming stream
                    String clientCommand = in.readLine();

                    System.out.println("Client Says :" + clientCommand);


                    if(clientCommand.equalsIgnoreCase("quit"))
                    {
                        // Special command. Quit this thread
                        m_bRunThread = false;   
                        System.out.print("Stopping client thread for client : " + m_clientID);
                    }
                    else
                    {
                        // Echo it back to the client.
                        out.println(clientCommand);
                        out.flush();
                    }
                }
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            finally
            {
                // Clean up
                try
                {                    
                    in.close();
                    out.close();
                    m_clientSocket.close();
                    System.out.println("...Stopped");
                }
                catch(IOException ioe)
                {
                    ioe.printStackTrace();
                }
            }
        }
    }
} 


#include <stdio.h>      
#include <sys/types.h>
#include <sys/socket.h>   
#include <netdb.h>

int main(int argc, char *argv[]) {

    int simpleSocket = 0;
    int simplePort = 0;
    int returnStatus = 0;
    char buffer[256] = "some string\n";
    char buff[256] = "quit\n";
    struct sockaddr_in simpleServer;

    if (3 != argc) {

        fprintf(stderr, "Usage: %s <server> <port>\n", argv[0]);
        exit(1);

    }

    /* create a streaming socket      */
    simpleSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (simpleSocket == -1) {

        fprintf(stderr, "Could not create a socket!\n");
        exit(1);

    }
    else {
        fprintf(stderr, "Socket created!\n");
    }

    /* retrieve the port number for connecting */
    simplePort = atoi(argv[2]);

    /* setup the address structure */
    /* use the IP address sent as an argument for the server address  */
    bzero(&simpleServer, sizeof(simpleServer)); 
    simpleServer.sin_family = AF_INET;
    inet_addr(argv[2], &simpleServer.sin_addr.s_addr);
    simpleServer.sin_port = htons(simplePort);

    /*  connect to the address and port with our socket  */
    returnStatus = connect(simpleSocket, (struct sockaddr *)&simpleServer, sizeof(simpleServer));

    if (returnStatus == 0) {
        fprintf(stderr, "Connect successful!\n");
    }
    else {
        fprintf(stderr, "Could not connect to address!\n");
    close(simpleSocket);
    exit(1);
    }

    send(simpleSocket, buffer, sizeof(buffer), 0);
    read(simpleSocket, buffer, sizeof(buffer), 0);
    send(simpleSocket, buffer, sizeof(buffer), 0);
    read(simpleSocket, buffer, sizeof(buffer), 0);
    send(simpleSocket, buffer, sizeof(buffer), 0);
    read(simpleSocket, buffer, sizeof(buffer), 0);
    send(simpleSocket, buffer, sizeof(buffer), 0);
    read(simpleSocket, buffer, sizeof(buffer), 0);
    send(simpleSocket, buffer, sizeof(buffer), 0);
    read(simpleSocket, buffer, sizeof(buffer), 0);
    send(simpleSocket, buffer, sizeof(buffer), 0);
    read(simpleSocket, buffer, sizeof(buffer), 0);
    send(simpleSocket, buff, sizeof(buff), 0);
//    read(simpleSocket, buffer, sizeof(buffer), 0);

    /* get the message from the server   */
//    returnStatus = read(simpleSocket, buffer, sizeof(buffer), 0);

        fprintf(stderr, "Return Status = %d \n", returnStatus);

    close(simpleSocket);
    return 0;

}

I get this error message into the Java server.

Accepted Client : ID - 2 : Address - localhost
Client Says :some string
Client Says :some string
Client Says :some string
Client Says :some string
Client Says :quit
Client Says :
Client Says :null
java.lang.NullPointerException
    at EchoServer$ClientServiceThread.run(EchoServer.java:102)
...Stopped

How I can fix this problem?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T19:23:19+00:00Added an answer on May 30, 2026 at 7:23 pm

    The problem is that clientCommand is null and as a result you get the NullPointerException.

    From your log output I see that you print quit and so you should have gone to the branch were you do m_bRunThread = false; and stop reading.

    But instead you continue printing/reading after that as show the logs.

    I suggest 2 things to try:
    Declare the boolean as volatile

    volatile boolean m_bRunThread = true;   
    

    and take into account empty space: clientCommand.trim().equalsIgnoreCase("quit")

    Actually do it defencively as follows:

     while(m_bRunThread) {                    
           // read incoming stream
           String clientCommand = in.readLine();    
           if(clientCommand == null || "".equals(clientCommand.trim()){  
             bRunThread = false;//here you could also do break and just use a while(true)  
           }  
           //go on with the code
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
I would like to count the length of a string with PHP. The string
For some reason, after submitting a string like this Jack’s Spindle from a text
I've got a string that has curly quotes in it. I'd like to replace
Specifically, suppose I start with the string string =hello \'i am \' me And

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.