简体   繁体   中英

Issues with Thread in C#

I have written the code for Server/Client program in C#. Without using the Thread , it is working fine. If I use Thread , I am getting following error message.

The thread '' (0x9a8) has exited with code 0 (0x0).

Sample code


public class MyServer{
    public MyServer (){
    ...
    ...
    System.Threading.Thread socThread = new System.Threading.Thread(new System.Threading.ThreadStart(receiveSockets));
    socThread.Start();
}

        private void receiveSockets()
        {
            try
            {
                while(true){
                IPAddress ipadd = IPAddress.Parse(systemIPAddress);
                TcpListener tcp = new TcpListener(ipadd, 8001);
                tcp.Start();
                Console.WriteLine("Waiting for client in 8001 port no");
                Socket socket = tcp.AcceptSocket();
                Console.WriteLine("Client address : " + socket.RemoteEndPoint);
                System.Threading.Thread socThread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(receiveData));
                socThread.Start(socket);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error in receive Sockets : " + e.Message);
            }
        }

        private void receiveData(object obj)
        {
            try
            {
                while(true){
                Socket socket = (Socket)obj;
                byte[] data = new byte[1000];
                int status = socket.Receive(data);
                Console.WriteLine("Received 1.");
                string content = Encoding.UTF8.GetString(data, 0, 1000);
                Console.WriteLine("Received data 1 : " + content);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error in receive Data : " + e.Message);
            }
        }
        static void Main(string[] args){
            MyServer server = new MyServer();
        }

Client Program

static void Main(string[] args)
{
            TcpClient tcp = new TcpClient();
            tcp.Connect("192.168.1.11", 8001);
            Stream stream = tcp.GetStream();
            String msg = "Testing...";
            byte[] content = new byte[msg.Length * sizeof(char)];
            System.Buffer.BlockCopy(msg.ToCharArray(), 0, content, 0, content.Length);
            stream.Write(content, 0, content.Length);
}

I am getting the following output.


IP Addrress : 192.168.1.11
Waiting for client in 8001 port no
Client address : 192.168.1.11:50140
The thread '' (0x9a8) has exited with code 0 (0x0).
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
The thread '' (0x1760) has exited with code 0 (0x0).
Error in receive Data : An existing connection was forcibly closed by the remote host
The program '[1396] Window_Server.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).

Please help me to fix this issue.

"The thread '' (0x9a8) has exited with code 0 (0x0)." is not an error. It is simply telling you that a background thread has exited. Zero means the thread ran and exited successfully.

The exception is in receiveData(object obj) as you should be able to tell, given the exception , "Error in receive Data : An existing connection was forcibly closed by the remote host".

If you post the client program you are working with I might be able to help.

You need to figure out why you are throwing a socket exception. If you read the documentation for Socket.Receive You would see this section:

Note

If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation in the MSDN library for a detailed description of the error.

Follwing that link shows you how to read the error code:

The ErrorCode property contains the error code that is associated with the error that caused the exception.

The default constructor for SocketException sets the ErrorCode property to the last operating system error that occurred. For more information about socket error codes, see the Windows Sockets version 2 API error code documentation in MSDN.

Which should bring you to the error codes page .

Now depending on your error code, which you have not provided, you can diagnose the network issue.

The problem is that Main() does not wait for the sockets to be done with their jobs. As soon as it has created the threads, it exists... And the threads are destroyed.

You need to wait for the socket-handling threads by using events of some sort, or by sleeping, from Main() - or from MyServer(), as long as the program exists only when the whole job is done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM