c#Thread继续使用socket运行

时间:2014-09-05 12:35:49

标签: c# multithreading sockets

我有一个程序,我需要从多个客户端监听,这些客户端在特定时间间隔之后从网络发送数据,然后插入到数据库中。我编写了一个多线程程序但是在监听时,一个线程随机地进入无限循环,而实际上并没有从客户端读取数据。 这是我的代码:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpListener serverSocket = new TcpListener(IPAddress.Parse("my.ip.add.ress"),myport);
            TcpClient clientSocket = default(TcpClient);
            int counter = 0;

            serverSocket.Start();
            Console.WriteLine(" >> " + "Server Started"); 

            counter = 0;
            while (true)
            {
                counter += 1;
                clientSocket = serverSocket.AcceptTcpClient();
                Console.WriteLine(" >> " + "Client No:" + Convert.ToString(counter) + " started!");
                handleClinet client = new handleClinet();
                client.startClient(clientSocket, Convert.ToString(counter));
            }
            clientSocket.Close();
            serverSocket.Stop();
            Console.WriteLine(" >> " + "exit");
            Console.ReadLine();
        }
    }

    //Class to handle each client request separatly
    public class handleClinet
    {
        TcpClient clientSocket;
        string clNo;
        public void startClient(TcpClient inClientSocket, string clineNo)
        {
            Console.WriteLine("In start client");
            this.clientSocket = inClientSocket;
            this.clNo = clineNo;
            Thread ctThread = new Thread(doChat);
            ctThread.Start();
        }
        private void doChat()
        {
            Console.WriteLine("In doChat");
            byte[] bytesFrom = new byte[251];
            string data = null;
            string connectionString = null;
            SqlConnection cnn ;
            connectionString = "some connection string";
            while ((true))
            {
                try
                {       
                    NetworkStream networkStream = clientSocket.GetStream();
                    networkStream.Read(bytesFrom, 0, bytesFrom.Length);
                    data = System.Text.Encoding.ASCII.GetString(bytesFrom);
                    //networkStream.Flush();
                    //Console.WriteLine(" >> " + "From client-" + clNo + data.Trim());
                    //get message type from device
                    String gMsgType = data.Slice(13,17);
                    Console.WriteLine("{0}",gMsgType);
                    //if the msg BP05 use it else continue
                    if(String.Compare("BP05",gMsgType) !=0 ) 
                        throw new Exception();
                    //we got bp05 message parse the inputs
                    String gId = data.Slice(18,32);
                    String gDate = data.Slice(32,38);
                    String gStatus = data.Slice(38,39);
                    String gLat = data.Slice(39,48);
                    String gLon = data.Slice(49,59);
                    String gSpeed = data.Slice(60,65);
                    String gTime = data.Slice(65,71);
                    String gInputs = data.Slice(77,85);
                    String gMileData = data.Slice(86,92);
                    if(String.Compare("A", gStatus)==0)
                    {
                        //sanitize inputs before insertion
//some operations
                        Console.WriteLine("{0}",data);
                        //connect to database
                        cnn = new SqlConnection(connectionString);         
                        cnn.Open();
                        SqlCommand com = new SqlCommand();
                        com.Connection = cnn;
                        com.CommandText = "some insert query"
                        com.ExecuteNonQuery();
                        cnn.Close();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(" >> " + ex.ToString());
                    break;
                }
            }
        }
    } 
}

2 个答案:

答案 0 :(得分:0)

首先,删除while(true)循环并使用某种条件。也许是一个“isRunning”布尔值,您可以根据需要更改为结束程序。其次,

networkStream.Read(bytesFrom, 0, bytesFrom.Length);

如果我没记错的话,应该返回从套接字读取的字节数。如果客户端已断开连接,则可以从套接字读取0个字节。如果从套接字读取0字节,我会从那里开始并中断。

答案 1 :(得分:0)

也许networkStream.Read是一个阻塞函数,为什么不尝试为Read函数设置超时?