0

我正在构建一个简单的从服务器向客户端传递消息的基本程序。

现在我能够成功地在服务器和客户端之间建立连接,但是客户端程序无法从流中读取。这是我的代码。

服务器程序代码

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

namespace chat_client_console
{
    class Program
    {
        static TcpListener listener;
        static void Main(string[] args)
        {
            string name = Dns.GetHostName();
            IPAddress[] address = Dns.GetHostAddresses(name);

            /*
            foreach(IPAddress addr in address)
            {
                Console.WriteLine(addr);
            }*/
            Console.WriteLine(address[1].ToString());
            listener = new TcpListener(address[1], 2055);

            listener.Start();

            Socket soc = listener.AcceptSocket();
            Console.WriteLine("Connection successful");
            Stream s = new NetworkStream(soc);

            StreamReader sr = new StreamReader(s);
            StreamWriter sw = new StreamWriter(s);

            sw.AutoFlush = true;
            sw.Write("A test message");
            Console.WriteLine("Test message delivered. Now ending the program");

            /*
            string name = Dns.GetHostName();
            Console.WriteLine(name);
            //IPHostEntry ip = Dns.GetHostEntry(name);
            //Console.WriteLine(ip.AddressList[0].ToString());
            IPAddress[] adr=Dns.GetHostAddresses(name);
            foreach (IPAddress adress in adr)
            {
                Console.WriteLine(adress);
            }
            */
            Console.ReadLine();
        }
    }
}

这是客户端程序的代码

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

namespace chat_client_console_client
{
    class Program
    {
        static void Main(string[] args)
        {
            string display;
            TcpClient client = new TcpClient("localhost", 2055);
            Stream s = client.GetStream();
            Console.WriteLine("Connection successfully received");

            StreamWriter sw = new StreamWriter(s);
            StreamReader sr = new StreamReader(s);
            sw.AutoFlush = true;
            while (true)
            {

                display = sr.ReadLine();
                Console.WriteLine("Reading stream");
                if (display == "")
                {
                    Console.WriteLine("breaking stream");
                    break;
                }

            }

            Console.WriteLine(display);
        }
    }
}

现在我能够成功地建立程序之间的连接,如各种检查消息所示。服务器程序也能够成功地将数据发送到流中。

但是,客户端程序无法从流中读取数据。它似乎卡在 readline() 函数上。

现在我已经在这个问题上撞了几个小时了,如果有人能够帮助我,我将不胜感激。

4

1 回答 1

5

看看你的服务器:

sw.AutoFlush = true;
sw.Write("A test message");

您永远不会写换行符,这是客户正在等待看到的。

于 2012-09-12T16:28:35.710 回答