服务器程序不会从Stream读取

时间:2013-12-05 12:46:10

标签: c# tcpclient tcplistener

我目前正在尝试编写TCP客户端/服务器应用程序。我觉得自己做得很差,因为我对C#(来自Java)很陌生。

我的客户有这段代码:

    public static void SendPlejeFamilieObjekt(PlejeFamilie pfamilie)
    {
        try
        {
            InitConnection();
            if (_isConnected)
            {
                _sWriter.WriteLine("SEND_PLEJEFAMILIE");

                if (_sReader.ReadLine().Equals("AUTH_GIVEN"))
                {
                    #region Send Plejefamilie Objekt
                    _sWriter.WriteLine(pfamilie.CPRKvinde);
                    _sWriter.WriteLine(pfamilie.CPRMand);
                    _sWriter.WriteLine(pfamilie.NavnKvinde);
                    _sWriter.WriteLine(pfamilie.NavnMand);
                    _sWriter.WriteLine(pfamilie.Addresse);
                    _sWriter.WriteLine(pfamilie.MobilKvinde);
                    _sWriter.WriteLine(pfamilie.MobilMand);
                    _sWriter.WriteLine(pfamilie.HjemmeTelefon);
                    _sWriter.WriteLine(pfamilie.StillingKvinde);
                    _sWriter.WriteLine(pfamilie.StillingMand);
                    _sWriter.WriteLine(pfamilie.EmailKvinde);
                    _sWriter.WriteLine(pfamilie.EmailMand);
                    _sWriter.WriteLine(pfamilie.EmailFaelles);
                    _sWriter.WriteLine(pfamilie.GodkendtDato.ToShortDateString());
                    _sWriter.WriteLine(pfamilie.PlejeForaeldreUdd);
                    _sWriter.WriteLine(pfamilie.AntalKurserIAar);
                    _sWriter.WriteLine(pfamilie.AntalBoernGodkendt);
                    _sWriter.WriteLine(pfamilie.Vilkaar);
                    _sWriter.WriteLine(pfamilie.Status);
                    #endregion Send Plejefamilie Objekt
                }
            }
        }
        finally
        {
            EndConnection();
        }
    }

它一直用于发送“SEND_PLEJEFAMILIE”。我通过打印到控制台检查了这一点。

现在在我的服务器代码中,它看起来像这样:

    private static void HandleClient(object obj)
    {
        TcpClient client = (TcpClient)obj;
        Console.WriteLine("Handling client: {0}", client.Client.LocalEndPoint.ToString());
        StreamWriter sWriter = new StreamWriter(client.GetStream(), Encoding.ASCII);
        StreamReader sReader = new StreamReader(client.GetStream(), Encoding.ASCII);
        Console.WriteLine("Streams Acquired");
        bool bClientConnected = client.Connected;
        Console.WriteLine("bClientConnected {0}", bClientConnected.ToString());
        String sData = sReader.ReadLine();
        List<String> list;
        List<Note> nList;
        List<Note> nList2;
        while (bClientConnected)
        {
            Console.WriteLine(sData);
            switch (sData)
            {
                #region Modtag Plejefamilie
                case "SEND_PLEJEFAMILIE":
                    Console.WriteLine("Receiving PlejeFamilie");
                    sWriter.WriteLine("AUTH_GIVEN");
                    sWriter.Flush();
                    Console.WriteLine("AUTH_GIVEN");
                    list = new List<String>();
                    while (!(sData = sReader.ReadLine()).Equals("END"))
                    {
                        list.Add(sData);
                    }
                    ServerPlejeFamilie spf = new ServerPlejeFamilie();
                    spf.Info = list;
                    pfStack.Push(spf);
                    Console.WriteLine("Received {0}", spf.Info[0]);
                    break;

程序在此行代码后停止运行:Console.WriteLine("bClientConnected {0}", bClientConnected.ToString());

我无法弄清楚原因。 以下是这两个类的所有代码,以备不时之需:

客户代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Smart_Journal.Familie;
using System.Net.Sockets;
using System.IO;
using System.Net;

namespace Smart_Journal
{
    /// <summary>
    /// DBM is our Database Manager. This will handle sending and receiving of data from the server.
    /// You should NOT call these functions directly. Instead, call the functions in the Utility class.
    /// </summary>
    public static class DBM
    {
        private static TcpClient _client;
        private static StreamReader _sReader;
        private static StreamWriter _sWriter;
        private static bool _isConnected;
        private static int portNum = 8888;
        private static String ipAddress = "127.0.0.1";

        private static void InitConnection()
        {
            _client = new TcpClient();
            _client.Connect(ipAddress, portNum);

            _sReader = new StreamReader(_client.GetStream(), Encoding.ASCII);
            _sWriter = new StreamWriter(_client.GetStream(), Encoding.ASCII);

            _isConnected = true;
        }

        private static void EndConnection()
        {
            _sWriter.WriteLine("END");

            _sReader.Close();
            _sWriter.Close();
            _client.Close();
            _isConnected = false;
        }

        public static void SendPlejeFamilieObjekt(PlejeFamilie pfamilie)
        {
            try
            {
                InitConnection();
                if (_isConnected)
                {
                    _sWriter.WriteLine("SEND_PLEJEFAMILIE");

                    if (_sReader.ReadLine().Equals("AUTH_GIVEN"))
                    {
                        #region Send Plejefamilie Objekt
                        _sWriter.WriteLine(pfamilie.CPRKvinde);
                        _sWriter.WriteLine(pfamilie.CPRMand);
                        _sWriter.WriteLine(pfamilie.NavnKvinde);
                        _sWriter.WriteLine(pfamilie.NavnMand);
                        _sWriter.WriteLine(pfamilie.Addresse);
                        _sWriter.WriteLine(pfamilie.MobilKvinde);
                        _sWriter.WriteLine(pfamilie.MobilMand);
                        _sWriter.WriteLine(pfamilie.HjemmeTelefon);
                        _sWriter.WriteLine(pfamilie.StillingKvinde);
                        _sWriter.WriteLine(pfamilie.StillingMand);
                        _sWriter.WriteLine(pfamilie.EmailKvinde);
                        _sWriter.WriteLine(pfamilie.EmailMand);
                        _sWriter.WriteLine(pfamilie.EmailFaelles);
                        _sWriter.WriteLine(pfamilie.GodkendtDato.ToShortDateString());
                        _sWriter.WriteLine(pfamilie.PlejeForaeldreUdd);
                        _sWriter.WriteLine(pfamilie.AntalKurserIAar);
                        _sWriter.WriteLine(pfamilie.AntalBoernGodkendt);
                        _sWriter.WriteLine(pfamilie.Vilkaar);
                        _sWriter.WriteLine(pfamilie.Status);
                        #endregion Send Plejefamilie Objekt
                    }
                }
            }
            finally
            {
                EndConnection();
            }
        }

        public static void SendPlejeBarnObjekt(PlejeBarn pbarn)
        {
            try
            {
                InitConnection();
                if (_isConnected)
                {
                    _sWriter.WriteLine("SEND_PLEJEBARN");

                    if (_sReader.ReadLine().Equals("AUTH_GIVEN"))
                    {
                        #region Send Plejebarn Objekt
                        _sWriter.WriteLine(pbarn.CPR);
                        _sWriter.WriteLine(pbarn.Navn);
                        _sWriter.WriteLine(pbarn.FolkeregisterAdresse);
                        _sWriter.WriteLine(pbarn.Email);
                        _sWriter.WriteLine(pbarn.Telefon);
                        _sWriter.WriteLine(pbarn.Sagsbehandler);
                        _sWriter.WriteLine(pbarn.Konsulent);
                        _sWriter.WriteLine(pbarn.Aflastning);
                        _sWriter.WriteLine(pbarn.NuvaerendeForanstaltning);
                        _sWriter.WriteLine(pbarn.AnbringelsesDato.ToShortDateString());
                        _sWriter.WriteLine(pbarn.UdskrivningsDato.ToShortDateString());
                        _sWriter.WriteLine("PLEJEBARN_B");

                        foreach (Note n in pbarn.Bemaerkninger)
                        {
                            _sWriter.WriteLine(n.Dato.ToShortDateString());
                            _sWriter.WriteLine(n.Navn);
                            _sWriter.WriteLine(n.Tekst);
                        }
                        _sWriter.WriteLine("END_PLEJEBARN_B");
                        _sWriter.WriteLine("PLEJEBARN_TF");

                        foreach (Note n in pbarn.TideligereForanstaltninger)
                        {
                            _sWriter.WriteLine(n.Dato);
                            _sWriter.WriteLine(n.Navn);
                            _sWriter.WriteLine(n.Tekst);
                        }
                        _sWriter.WriteLine("END_PLEJEBARN_TF");
                        #endregion Send Plejebarn Objekt
                    }
                }
            }
            finally
            {
                EndConnection();
            }
        }

        public static void SendBiologiskFamilieObjekt(BiologiskFamilie bfamilie)
        {
            try
            {
                InitConnection();
                if (_isConnected)
                {
                    _sWriter.WriteLine("SEND_BIOLOGISKFAMILIE");

                    if (_sReader.ReadLine().Equals("AUTH_GIVEN"))
                    {
                        #region Send Biologiskfamilie Objekt
                        _sWriter.WriteLine(bfamilie.CPRMor);
                        _sWriter.WriteLine(bfamilie.CPRFar);
                        _sWriter.WriteLine(bfamilie.NavnMor);
                        _sWriter.WriteLine(bfamilie.NavnFar);
                        _sWriter.WriteLine(bfamilie.Addresse);
                        _sWriter.WriteLine(bfamilie.MobilMor);
                        _sWriter.WriteLine(bfamilie.MobilFar);
                        _sWriter.WriteLine(bfamilie.HjemmeTelefon);
                        _sWriter.WriteLine(bfamilie.EmailMor);
                        _sWriter.WriteLine(bfamilie.EmailFar);
                        _sWriter.WriteLine(bfamilie.EmailFaelles);
                        _sWriter.WriteLine(bfamilie.ForaeldreMyndighed);
                        #endregion Send Biologiskfamilie Objekt
                    }
                }
            }
            finally
            {
                EndConnection();
            }
        }

        public static PlejeFamilie HentPlejeFamilieObjekt(String s)
        {
            return null;
        }

        public static PlejeBarn HentPlejeBarnObjekt(String s)
        {
            return null;
        }

        public static BiologiskFamilie HentBiologiskFamilie(String s)
        {
            return null;
        }
    }
}

服务器代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Smart_Journal_Server
{
    class Program
    {
        private static TcpListener _server;
        private static bool _isRunning;
        private static int port;
        private static Stack<ServerPlejeFamilie> pfStack = new Stack<ServerPlejeFamilie>();
        private static Stack<ServerPlejeBarn> pbStack = new Stack<ServerPlejeBarn>();
        private static Stack<ServerBiologiskFamilie> bfStack = new Stack<ServerBiologiskFamilie>();
        private static Stack<Request> rStack = new Stack<Request>();

        static void Main(string[] args)
        {
            args = new string[1];
            args[0] = "8888";
            if (args.Length == 0)
            {
                return;
            }
            else
            {
                port = Convert.ToInt32(args[0]);
            }
            Console.WriteLine("Booting up Server with port number {0}...", port);
            _server = new TcpListener(IPAddress.Any, port);
            Console.WriteLine("IP Address Assigned: {0}", IPAddress.Parse(((IPEndPoint)_server.LocalEndpoint).Address.ToString()));
            _server.Start();
            Console.WriteLine("Server Successfully Started");

            _isRunning = true;

            Thread t = new Thread(new ParameterizedThreadStart(SendToDataBase));
            Thread t1 = new Thread(new ParameterizedThreadStart(RetrieveFromDataBase));
            t.Start();
            Console.WriteLine("Ready to write data to the Database");
            t1.Start();
            Console.WriteLine("Ready to read data from the Database");
            LoopClients();
        }

        private static void SendToDataBase(object obj)
        {
            while (_isRunning)
            {
                if (pfStack.Count > 0)
                {
                    ServerPlejeFamilie pfobj = pfStack.Pop();
                    Console.WriteLine("Popping PlejeFamilieObject: {0}", pfobj.Info[0] + "," + pfobj.Info[1]);
                }

                if (pbStack.Count > 0)
                {
                    ServerPlejeBarn pbobj = pbStack.Pop();
                    Console.WriteLine("Popping PlejeBarnObject: {0}", pbobj.Info[0]);
                }

                if (bfStack.Count > 0)
                {
                    ServerBiologiskFamilie bfobj = bfStack.Pop();
                    Console.WriteLine("Popping BiologiskFamilieObject: {0}", bfobj.Info[0] + "," + bfobj.Info[1]);
                }
            }
        }

        private static void RetrieveFromDataBase(object obj)
        {
            while (_isRunning)
            {

            }
        }

        private static void LoopClients()
        {
            while (_isRunning)
            {
                //wait for client connection
                TcpClient newClient = _server.AcceptTcpClient();

                Thread t = new Thread(new ParameterizedThreadStart(HandleClient));
                t.Start(newClient);
            }
        }

        private static void HandleClient(object obj)
        {
            TcpClient client = (TcpClient)obj;
            Console.WriteLine("Handling client: {0}", client.Client.LocalEndPoint.ToString());
            StreamWriter sWriter = new StreamWriter(client.GetStream(), Encoding.ASCII);
            StreamReader sReader = new StreamReader(client.GetStream(), Encoding.ASCII);
            Console.WriteLine("Streams Acquired");
            bool bClientConnected = client.Connected;
            Console.WriteLine("bClientConnected {0}", bClientConnected.ToString());
            String sData = sReader.ReadLine();
            List<String> list;
            List<Note> nList;
            List<Note> nList2;
            while (bClientConnected)
            {
                Console.WriteLine(sData);
                switch (sData)
                {
                    #region Modtag Plejefamilie
                    case "SEND_PLEJEFAMILIE":
                        Console.WriteLine("Receiving PlejeFamilie");
                        sWriter.WriteLine("AUTH_GIVEN");
                        sWriter.Flush();
                        Console.WriteLine("AUTH_GIVEN");
                        list = new List<String>();
                        while (!(sData = sReader.ReadLine()).Equals("END"))
                        {
                            list.Add(sData);
                        }
                        ServerPlejeFamilie spf = new ServerPlejeFamilie();
                        spf.Info = list;
                        pfStack.Push(spf);
                        Console.WriteLine("Received {0}", spf.Info[0]);
                        break;
                    #endregion Modtag Plejefamilie
                    #region Modtag Plejebarn
                    case "SEND_PLEJEBARN":
                        sWriter.WriteLine("AUTH_GIVEN");
                        sWriter.Flush();
                        list = new List<String>();
                        nList = new List<Note>();
                        nList2 = new List<Note>();
                        while (!(sData = sReader.ReadLine()).Equals("END"))
                        {
                            if (sData.Equals("PLEJEBARN_B"))
                            {
                                do
                                {
                                    Note n = new Note();
                                    n.Dato = Convert.ToDateTime(sReader.ReadLine());
                                    n.Navn = sReader.ReadLine();
                                    n.Tekst = sReader.ReadLine();
                                    nList.Add(n);

                                    sData = sReader.ReadLine();
                                } while (!sData.Equals("END_PLEJEBARN_B"));
                            }
                            else if (sData.Equals("PLEJEBARN_TF"))
                            {
                                do
                                {
                                    Note n = new Note();
                                    n.Dato = Convert.ToDateTime(sReader.ReadLine());
                                    n.Navn = sReader.ReadLine();
                                    n.Tekst = sReader.ReadLine();
                                    nList2.Add(n);
                                    sData = sReader.ReadLine();
                                } while (!sData.Equals("END_PLEJEBARN_TF"));
                            }
                            else
                            {
                                list.Add(sData);
                            }
                        }
                        ServerPlejeBarn spb = new ServerPlejeBarn();
                        spb.Info = list;
                        spb.Bemaerkninger = nList;
                        spb.TideligereForanstaltninger = nList2;
                        pbStack.Push(spb);
                        Console.WriteLine("Received {0}", spb.Info[0]);
                        break;
                    #endregion Modtag Plejebarn
                    #region Modtag Biologisk Familie
                    case "SEND_BIOLOGISKFAMILIE":
                        sWriter.WriteLine("AUTH_GIVEN");
                        sWriter.Flush();
                        list = new List<String>();
                        while (!(sData = sReader.ReadLine()).Equals("END"))
                        {
                            list.Add(sData);
                        }
                        ServerBiologiskFamilie sbf = new ServerBiologiskFamilie();
                        sbf.Info = list;
                        bfStack.Push(sbf);
                        Console.WriteLine("Received {0}", sbf.Info[0]);
                        break;
                    #endregion Modtag Biologisk Familie
                    default:
                        sWriter.WriteLine("NO_AUTH");
                        break;
                }
            }
            sWriter.Close();
            sReader.Close();
            client.Close();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试添加_sWriter.Flush();在_sWriter.WriteLine之后(“SEND_PLEJEFAMILIE”);在客户端代码中。