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 8873179
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T18:24:01+00:00 2026-06-14T18:24:01+00:00

Heres my Server Code using System; using System.IO; using System.Net.Sockets; using System.Text; using System.Collections;

  • 0

Heres my Server Code

 using System;
    using System.IO;
    using System.Net.Sockets;
    using System.Text;
    using System.Collections;
    using System.Threading;

    public class SynchronousSocketListener
    {

    private const int portNum = 4444;
    private static ArrayList ClientSockets;
    private static bool ContinueReclaim = true;
    private static Thread ThreadReclaim;

    public static void StartListening()
    {

        ClientSockets = new ArrayList();

        ThreadReclaim = new Thread(new ThreadStart(Reclaim));
        ThreadReclaim.Start();

        TcpListener listener = new TcpListener(portNum);
        try
        {
            listener.Start();

            int TestingCycle = 3;
            int ClientNbr = 0;

            // Start listening for connections.
            Console.WriteLine("Waiting for a connection...");
            while (TestingCycle > 0)
            {

                TcpClient handler = listener.AcceptTcpClient();

                if (handler != null)
                {
                    Console.WriteLine("Client#{0} accepted!", ++ClientNbr);
                    // An incoming connection needs to be processed.
                    lock (ClientSockets.SyncRoot)
                    {
                        int i = ClientSockets.Add(new ClientHandler(handler));
                        ((ClientHandler)ClientSockets[i]).Start();
                        Console.WriteLine("Added sock {0}", i);
                    }
                    --TestingCycle;
                }
                else
                    break;
            }
            listener.Stop();

            ContinueReclaim = false;
            ThreadReclaim.Join();

            foreach (Object Client in ClientSockets)
            {
                ((ClientHandler)Client).Stop();
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        Console.WriteLine("\nHit enter to continue...");
        Console.Read();

    }

    private static void Reclaim()
    {
        while (ContinueReclaim)
        {
            lock (ClientSockets.SyncRoot)
            {
                for (int x = ClientSockets.Count - 1; x >= 0; x--)
                {
                    Object Client = ClientSockets[x];
                    if (!((ClientHandler)Client).Alive)
                    {
                        ClientSockets.Remove(Client);
                        Console.WriteLine("A client left");
                    }
                }
            }
            Thread.Sleep(200);
        }
    }


    public static int Main(String[] args)
    {
        while (true)
        {
            StartListening();
        }
        return 0;
    }
}

class ClientHandler
{

    TcpClient ClientSocket;
    bool ContinueProcess = false;
    Thread ClientThread;

    public ClientHandler(TcpClient ClientSocket)
    {
        this.ClientSocket = ClientSocket;
    }

    public void Start()
    {
        ContinueProcess = true;
        ClientThread = new Thread(new ThreadStart(Process));
        ClientThread.Start();
    }

    private void Process()
    {

        // Incoming data from the client.
        string data = null;

        // Data buffer for incoming data.
        byte[] bytes;

        if (ClientSocket != null)
        {
            NetworkStream networkStream = ClientSocket.GetStream();
            ClientSocket.ReceiveTimeout = 100; // 1000 miliseconds

            while (ContinueProcess)
            {
                bytes = new byte[ClientSocket.ReceiveBufferSize];
                try
                {

                    int BytesRead = networkStream.Read(bytes, 0, (int)ClientSocket.ReceiveBufferSize);
                    //BytesRead--;
                    if (BytesRead > 0)
                    {
                        Console.WriteLine("Bytes Read - Debugger " + BytesRead);
                        data = Encoding.ASCII.GetString(bytes, 0, BytesRead);

                        // Show the data on the console.
                        Console.WriteLine("Text received : {0}", data);

                        // Echo the data back to the client.
                        byte[] sendBytes = Encoding.ASCII.GetBytes("I rec ya abbas");
                        networkStream.Write(sendBytes, 0, sendBytes.Length);

                        if (data == "quit") break;

                    }
                }
                catch (IOException) { } // Timeout
                catch (SocketException)
                {
                    Console.WriteLine("Conection is broken!");
                    break;
                }
                Thread.Sleep(200);
            } // while ( ContinueProcess )
            networkStream.Close();
            ClientSocket.Close();
        }
    }  // Process()

    public void Stop()
    {
        ContinueProcess = false;
        if (ClientThread != null && ClientThread.IsAlive)
            ClientThread.Join();
    }

    public bool Alive
    {
        get
        {
            return (ClientThread != null && ClientThread.IsAlive);
        }
    }

} // class ClientHandler 

Heres my Client Code:

package com.example.socketclient;


import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.BufferedWriter; 
import java.io.IOException; 
import java.io.InputStream;
import java.io.OutputStreamWriter; 
import java.io.InputStreamReader;
import java.io.PrintWriter; 
import java.net.InetAddress; 
import java.net.Socket; 
import java.net.UnknownHostException; 
import android.util.Log; 

public class SocketCode extends Activity {

    public TextView txt;
    protected SocketCore Conn;
    public Button b;
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_socket_code);
        b = (Button)findViewById(R.id.button1);
        txt = (TextView)findViewById(R.id.textView1);
        Conn = new SocketCore(this,txt);
        b.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                Conn.execute();

            }
        });






    }

}

SocketCore

package com.example.socketclient;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.app.ProgressDialog;

import android.content.Context;

import android.os.AsyncTask;
import android.os.SystemClock;

import android.os.Bundle;

import android.util.Log;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;


class SocketCore extends AsyncTask<Context, Integer, String>
{
    String text = "";
    String finalText = "";
    private Context ctx;
    ProgressDialog dialog;
    TextView Msg;
    Socket socket;
    public SocketCore(Context applicationContext,TextView Change) 
    {
        // TODO Auto-generated constructor stub
        ctx = applicationContext;
        dialog = new ProgressDialog(applicationContext);
        Msg = Change;
    }

    @Override
    protected String doInBackground(Context... arg0) {
        // TODO Auto-generated method stub

         try { 
                InetAddress serverAddr = InetAddress.getByName("192.168.0.150"); 
                Log.d("TCP", "C: Connecting....");

                socket = new Socket(serverAddr,4444); 
               // Log.d("TCP", "C: I dunno ...");
                String message = "Hello Server .. This is the android client talking to you .. First we are testing Server Crashing";

                PrintWriter out = null;
                BufferedReader in = null;

                try { 
                    Log.d("TCP", "C: Sending: '" + message + "'"); 
                    out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true); 
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));                
                   //serverReturnString = System.Text.Encoding.ASCII.GetString(response, 0, bytes);

                    out.println("quit");
                   //out.print("h");
                    while ((text = in.readLine()) != null) {
                        finalText += text;
                      if(text=="quit")
                      {
                          socket.close();
                      }
                        Log.d("TCP", "C: Done."+finalText);
                        }

               //   Msg.setText("LOLZ");
                    Log.d("TCP", "C: Sent."); 



                } catch(Exception e) { 
                    Log.e("TCP", "S: Error", e); 
                } /*finally { 
                    socket.close(); 
                    Log.d("TCP", "S: Closed"); 
                } */

            }catch (UnknownHostException e) { 
                // TODO Auto-generated catch block 
                Log.e("TCP", "C: UnknownHostException", e); 
                e.printStackTrace(); 
            } catch (IOException e) { 
                // TODO Auto-generated catch block 
                Log.e("TCP", "C: IOException", e); 
                e.printStackTrace(); 
            }       
           //dialog.setMessage("Recieved: "+finalText);

        return "COMPLETE";
    }
    protected void onPostExecute(String x)
    {
        super.onPostExecute("Finished");
        dialog.dismiss();
        Msg.setText(finalText);

    }
    protected void onPreExecute()
    {dialog.setTitle("Initializing Connection");
    dialog.setMessage("Connecting");

        dialog.show();
    }

}

Server can read from android phone also the android client get message from server.
The Problem is whenever The Server detects connection and start Receives text and Sends Reply . The code doesnt accept more connection after that .

Note:
I tried to to test using C# client it works fine so i got a problem on the client side

  • 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-06-14T18:24:03+00:00Added an answer on June 14, 2026 at 6:24 pm

    You can’t use more then AsyncTask.

    The simplest approach is to move the code inside doInBackground() to a Runnable and then start a new Thread with that runnable on every click.

    Example:

    private Runnable rSocketCore = new Runnable() {
        public void run() {
              //here goes your connection code
        }
    };
    
    
        b.setOnClickListener(new View.OnClickListener() {
    
            public void onClick(View v) {
                 new Thread(rSocketCore).start();
            }
    

    Note: You will also need an Handler if you want to communicate from the thread to the UI.

    Regards.

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

Sidebar

Related Questions

Here is the server code package echoserver; import java.net.*; import java.io.*; public class EchoServer
I'm working on a web client. Here is the code: using System.Net; using System.Net.Sockets;
Here is my code: using System; using System.Net; using MailListClient.MailListServiceReference; using Microsoft.Exchange.WebServices.Autodiscover; using Microsoft.Exchange.WebServices.Data;
Using the obsolete System.Web.Mail sending email works fine, here's the code snippet: Public Shared
I'm stuck here: I need to get the values of org.jboss.system.server.ServerInfo With the code
Here's the code. public class testClient { public static void main(String[] args) { testClient
I have a Java client that connects to a C++ server using TCP Sockets
Cannot access a disposed object. Object name: 'System.Net.Sockets.TcpClient'. I don't understand why it happen
I am writing a client-server application using TCP Sockets. The server is written in
I am using TCP/IP sockets to create a client and server applicaton. Originally I

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.