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

  • SEARCH
  • Home
  • 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 7597363
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T22:08:21+00:00 2026-05-30T22:08:21+00:00

I’m working on this example with C threaded server and java client. This is

  • 0

I’m working on this example with C threaded server and java client. This is the server:

#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>

void* thread_proc(void *arg);

int main(int argc, char *argv[])
{
    struct sockaddr_in sAddr;
    int listensock;
    int result;
    int nchildren = 6;
    pthread_t thread_id;
    int x;
    int val;

    listensock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    val = 1;
    result = setsockopt(listensock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
    if (result < 0) {
        perror("server");
        return 0;
    }

    sAddr.sin_family = AF_INET;
    sAddr.sin_port = htons(6000);
    sAddr.sin_addr.s_addr = INADDR_ANY;

    result = bind(listensock, (struct sockaddr *) &sAddr, sizeof(sAddr));
    if (result < 0) {
        perror("exserver5");
        return 0;
    }

    result = listen(listensock, 5);
    if (result < 0) {
        perror("exserver5");
        return 0;
    }

   for (x = 0; x < nchildren; x++) {
    result = pthread_create(&thread_id, NULL, thread_proc, (void *) listensock);
    if (result != 0) {
      printf("Could not create thread.\n");
      return 0;
    }
    sched_yield();
    }

   pthread_join (thread_id, NULL);
}

void* thread_proc(void *arg)
{
  int listensock, sock;
  char buffer[25];
  int nread;

  listensock = (int) arg;

  while (1) {
    sock = accept(listensock, NULL, NULL);
    printf("client connected to child thread %i with pid %i.\n", pthread_self(), getpid());

    while(1){
        nread = recv(sock, buffer, 25, 0);
        buffer[nread] = '\0';
        printf("%s\n", buffer);
        send(sock, buffer, nread, 0);
        if(nread == '9'){
        close(sock);
        }
        }

    printf("client disconnected from child thread %i with pid %i.\n", pthread_self(), getpid());
  }
}

This is the Java client:

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

// A client for our multithreaded EchoServer.
public class client
{
    public static void main(String[] args)
    {
        Socket s = null;

        // Create the socket connection to the EchoServer.
        try
        {
            s = new Socket("localhost", 6000);
        }        
        catch(UnknownHostException uhe)
        {
            // Host unreachable
            System.out.println("Unknown Host");
            s = null;
        }
        catch(IOException ioe)
        {
            // Cannot connect to port on given host
            System.out.println("Cant connect to server at 6000. Make sure it is running.");
            s = null;
        }

        if(s == null)
            System.exit(-1);

        BufferedReader in = null;
        PrintWriter out = null;

        try
        {
            // Create the streams to send and receive information
            in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));

            // Since this is the client, we will initiate the talking.
            // Send a string.
            out.println("Hello");
            out.flush();
            // receive the reply.
            System.out.println("Server Says : " + in.readLine());

            // Send a string.
            out.println("This");
            out.flush();
            // receive a reply.
            System.out.println("Server Says : " + in.readLine());

            // Send a string.
            out.println("is");
            out.flush();
            // receive a reply.
            System.out.println("Server Says : " + in.readLine());

            // Send a string.
            out.println("a");
            out.flush();
            // receive a reply.
            System.out.println("Server Says : " + in.readLine());

            // Send a string.
            out.println("Test");
            out.flush();
            // receive a reply.
            System.out.println("Server Says : " + in.readLine());

            // Send the special string to tell server to quit.
            out.println("9");
            out.flush();
        }
        catch(IOException ioe)
        {
            System.out.println("Exception during communication. Server probably closed connection.");
        }
        finally
        {
            try
            {
                // Close the streams
                out.close();
                in.close();
                // Close the socket before quitting
                s.close();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }                
        }        
    }
} 

When I run the client this is the output:

[root@localhost java]# /opt/jdk1.7.0_03/bin/java client
Server Says : Hello
Server Says : This
Server Says : is
Server Says : a
Server Says : Test
[root@localhost java]# 

When I run the server this is the output:

[root@localhost java]# ./server 
client connected to child thread -1215423632 with pid 2854.
Hello

This

is

a

Test

9

9

[root@localhost java]# 

When the client closes the connection the server crashes. I want to close the connection without destroying the thread. How I can fix the problem?

Best wishes

P.S This is the original threads code which accepts connections.

void* thread_proc(void *arg)
{
  int listensock, sock;
  char buffer[25];
  int nread;

  listensock = (int) arg;

  while (1) {
    sock = accept(listensock, NULL, NULL);
    printf("client connected to child thread %i with pid %i.\n", pthread_self(), getpid());
    nread = recv(sock, buffer, 25, 0);
    buffer[nread] = '\0';
    printf("%s\n", buffer);
    send(sock, buffer, nread, 0);
    close(sock);
    printf("client disconnected from child thread %i with pid %i.\n", pthread_self(), getpid());
  }
}

This loop will accept only one string and will return it. Then will exit. I modify it with a while loop but with the inner while loop(see above) the server crashes.
How I can modify the code so that the thread can accept many strings and send many strings?

  • 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-30T22:08:22+00:00Added an answer on May 30, 2026 at 10:08 pm
    while (1) {
        sock = accept(listensock, NULL, NULL);
        printf("client connected to child thread %i with pid %i.\n", pthread_self(), getpid());
    
        nread = 0;
        while(nread >= 0) {
            nread = recv(sock, buffer, 25, 0);
            if (nread >= 0) {
                buffer[nread] = '\0';
                printf("%s\n", buffer);
                send(sock, buffer, nread, 0);
            }
        }
        close(sock);
        printf("client disconnected from child thread %i with pid %i.\n", pthread_self(), getpid());
    

    }

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
Does anyone know how can I replace this 2 symbol below from the string
i got an object with contents of html markup in it, for example: string
I have thousands of HTML files to process using Groovy/Java and I need to
I'm working with an upstream system that sometimes sends me text destined for HTML/XML
I have this code to decode numeric html entities to the UTF8 equivalent character.

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.