Click here to Skip to main content
13,148,260 members (56,389 online)
Rate this:
Please Sign up or sign in to vote.
I'm using .NET synchronous socket to send data from a client to server.
I need to get the data from the StartListening() method to use it in the Main() but
the variable data is inside an infinite loop ( while(true)).
Any help please?
This is the server code :
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class SynchronousSocketListener
    byte[] bytes = new Byte[1024];
    IPHostEntry ipHostInfo;
    IPAddress ipAddress ;
    IPEndPoint localEndPoint;
    Socket listener;
   // Incoming data from the client.
    public static string data = null;
    // Volatile is used as hint to the compiler that this data
    // member will be accessed by multiple threads.
    private volatile bool _shouldStop;
    public  void InitializeListening()
        // Data buffer for incoming data.
        // Establish the local endpoint for the socket.
        // Dns.GetHostName returns the name of the 
        // host running the application.
         ipHostInfo = Dns.Resolve("localhost");
         ipAddress = ipHostInfo.AddressList[0];
         localEndPoint = new IPEndPoint(ipAddress, 11007);
        // Create a TCP/IP socket.
        listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    public void StopListening()
        _shouldStop = true;
        byte[] msg = Encoding.ASCII.GetBytes("please stop!");
        // Create a TCP/IP  socket.
        Socket sender = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);
            // Connect the socket to the remote endpoint. Catch any errors.
            try {
                // Send the data through the socket.
                int bytesSent = sender.Send(msg);
                // Release the socket.
            catch (ArgumentNullException ane)
                Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
            catch (SocketException se)
                Console.WriteLine("SocketException : {0}", se.ToString());
            catch (Exception e)
                Console.WriteLine("Unexpected exception : {0}", e.ToString());
    public  void StartListening()
        // Bind the socket to the local endpoint and 
        // listen for incoming connections.
            // Start listening for connections.
            while (true)
                Console.WriteLine("Waiting for a connection...");
                // Thread is suspended while waiting for an incoming connection.
                Socket handler = listener.Accept();
                // An incoming connection needs to be processed.
                if (_shouldStop)
                data = null;
                while (true)
                    bytes = new byte[1024];
                    int bytesRec = handler.Receive(bytes);
                    data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    if (data.IndexOf("<EOF>") > -1)
                // Show the data on the console.
                Console.WriteLine("Text received : {0}", data);
                // Echo the data back to the client.
                //byte[] msg = Encoding.ASCII.GetBytes(data);
                byte[] msg = Encoding.ASCII.GetBytes("Salam !");
        catch (Exception e)
    public static int Main(String[] args)
        Console.WriteLine("I am the Synchronous Socket Server\n");
        SynchronousSocketListener pServer = new SynchronousSocketListener();
        Thread serverkerThread = new Thread(pServer.StartListening);
        // Loop until server thread activates.
        while (!serverkerThread.IsAlive) ;
        Console.WriteLine("listening thread sevice started...\n");
        Console.WriteLine("\nPress Q when you want to quit...\n");
        int car;
            car = Console.Read();
            if (car == 81)
                // Request that the worker thread stop itself:
                // Use the Join method to block the current process 
                // until the object's thread terminates.
        } while (true);
        Console.WriteLine("listening thread sevice stopped and program will be exited...\n");
        return 0;
Posted 3-Apr-13 22:34pm

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Other than the problem that data is initialized to null and will throw an exception when you concatenate to it with += (initialize to string.Empty instead), I don't see the problem right off.
data should be accessible from the Main.
However, you'll want/need to use some form of synchronization between the threads.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web01 | 2.8.170924.2 | Last Updated 4 Apr 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100