TcpListener客户端保持连接状态,发送多条消息,但服务器仅接收或处理第一条消息

时间:2019-01-15 22:54:31

标签: c# multithreading tcplistener

我正在设置服务器以使用TcpListener读取某些网络客户端。客户端发送一些数据,我验证数据并对该数据发送响应,客户端保持连接状态并发送第二个响应,我验证数据并发送回响应,就像两次登录服务器一样。第一次登录可以很好地发送回客户端,但是第二次客户端响应时,服务器未显示它已从客户端接收到更多数据。

我已经通过设置虚拟客户端(真实的客户端是基于手机的ODB2)对其进行了测试。通过设置虚拟客户端,我确实验证了第一次握手已发生,但是当客户端发送第二组文本时,它没有显示在服务器上。

class Program
{
    static private TcpListener listener = null;
    static private TcpClient client = null;
    static private NetworkStream stream = null;
    static private int iCount = 0;
    static Int32 port = 8090;
    static IPAddress localAddr = IPAddress.Parse("192.168.1.17");
    static void Main(string[] args)
    {
        listener = new TcpListener(localAddr, port);
        listener.Start();
        while (true)
        {
            try
            {
                client = listener.AcceptTcpClient();
                ThreadPool.QueueUserWorkItem(ThreadProc, client);
            }
            catch (IOException ioex)
            {
                RestartStream();
            }
        }
    }
        private static void ThreadProc(object obj)
        {

        var client = (TcpClient)obj;
        Byte[] bytes = new Byte[client.ReceiveBufferSize];
        stream = client.GetStream();
        try
        {
            int bytesRead = stream.Read(bytes, 0, (int)client.ReceiveBufferSize);
            string returndata = Encoding.ASCII.GetString(bytes, 0, bytesRead).Replace("-", "");
            byte[] sendBytes;
            if (returndata.ToLower().StartsWith("7e") && returndata.ToLower().EndsWith("7e"))
            {
             //… do stuff with the data and send it back to the client 
             sendBytes = Encoding.Default.GetBytes(login1);
             stream.Write(sendBytes, 0, sendBytes.Length);
             stream.Flush();
                              }
                              else
                {
                    SaveStream(returndata);
                }
            }
        catch (Exception ex)
        {
                      Console.WriteLine(ex.ToString());
        }
    } 

测试客户端代码:

 //---data to send to the server---
        string textToSend = "7E010000360141850000080000000000000000000000000000000000000000000000000000000000000035303030303038003131313131313131313131313131313131F67E";

        //---create a TCPClient object at the IP and port no.---
        TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
        NetworkStream nwStream = client.GetStream();
        byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);

        //---send the text---
        Console.WriteLine("Sending : " + textToSend);
        nwStream.Write(bytesToSend, 0, bytesToSend.Length);

        //---read back the text---
        byte[] bytesToRead = new byte[client.ReceiveBufferSize];
        int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
        Console.WriteLine("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));

        string Text2 = "7E0100003601418535303030303038003131313131313131313131313131313131F67E";
        Console.WriteLine("Sending : " + Text2);
        byte[] bytesToSend2 = ASCIIEncoding.ASCII.GetBytes(Text2);
        nwStream.Write(bytesToSend2, 0, bytesToSend2.Length);
        client.Close();
        Console.ReadLine();

我需要做的是,我的理解是客户端一直保持连接状态并一遍又一遍地发送数据,我的系统似乎只接受一次然后停止接收,我需要它继续接收客户端数据,处理它。

1 个答案:

答案 0 :(得分:0)

好,所以我想通了,应该在线程旁边进行第二次while循环。

static void Main(string[] args)
    {
        listener = new TcpListener(localAddr, port);
        var clientSocket = default(TcpClient);
        listener.Start();
        var counter = 0;
        while (true)
        {
            clientSocket = listener.AcceptTcpClient();
            var client = new ConnectedDevice();
            client.startClient(clientSocket, counter.ToString(), sqlConnString);
        }
    }

ConnectedDevice类:

class ConnectedDevice
{
    private TcpClient _clientSocket;
    private string _clientNumber;
    private string _sqlConnString;

    public void startClient(TcpClient clientSocket, string clientNumber, string sqlConnString)
    {
        _clientSocket = clientSocket;
        _clientNumber = clientNumber;
        _sqlConnString = sqlConnString;

        var ctThread = new Thread(ProcessClient);
        ctThread.Start();
    }
    private void ProcessClient()
    {
        while (_clientSocket.Connected)
        {
            try
            {
                Byte[] bytes = new Byte[_clientSocket.ReceiveBufferSize];
                var networkStream = _clientSocket.GetStream();
                networkStream.ReadTimeout = 10000;
                int i;
                while ((i = networkStream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    var data = System.Text.Encoding.ASCII.GetString(bytes, 0, i).Replace("-", "");
                    byte[] sendBytes;
                    Console.WriteLine(data);
                    string sLogin1 = "7E81000013014185000008000000000054523230313731303138303930303137497E";
                    sendBytes = Encoding.ASCII.GetBytes(sLogin1);
                    networkStream.Write(sendBytes, 0, sendBytes.Length);
                    networkStream.Flush();
                }
            }
            catch (Exception ex)
            {

            }
        }
    }
}