c# - C# 中的简单客户端服务器应用程序

标签 c# visual-studio sockets network-programming tcpclient

我正在尝试构建一个简单的客户端服务器应用程序,其中服务器持续监听并且客户端可以发送消息。我正在使用 http://brunov.info/blog/2013/02/09/tcpip-client-server-application-exchange-with-string-messages/作为引用。但是,当我在 client.exe 的控制台上输入时,没有消息发送到服务器并且程序挂断了。我究竟做错了什么。请指教。

问候

这是我的 Server.cs

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

namespace ucSim1
{
    class Program
    {
        static void Main(string[] args)
        {
            var loaclAddress = IPAddress.Parse("127.0.0.1");
            var tcpListener = new TcpListener(loaclAddress, 81);
            tcpListener.Start();

            while (true)
            {
                Console.WriteLine("Waiting for a connection");

                var tcpClient = tcpListener.AcceptTcpClient();
                Console.WriteLine("Client Accepted");

                Thread thread = new Thread(() => ClientSession(tcpClient))
                {
                    IsBackground = true
                };

                thread.Start();
                Console.WriteLine( "Client Session thread started");

            }

        }

        private static bool tryRead(Stream stream, byte[] buffer, int offset, int count)
        {
            int bytesRead;
            while (count > 0 && (bytesRead = stream.Read(buffer, offset, count)) > 0)
            {
                offset += bytesRead;
                count -= bytesRead;
            }
            return count == 0;
        }



        private static void ClientSession(TcpClient tcpClient)
        {
            const int totalByteBuffer = 4096;
            byte[] buffer = new byte[256];

            using (var networkStream = tcpClient.GetStream())
            using (var bufferedStream = new BufferedStream(networkStream, totalByteBuffer))
                while (true)
                {
                    if (!tryRead(bufferedStream, buffer, 0, 1))
                    {
                        break;
                    }
                    byte messageLen = buffer[0];
                    if (!tryRead(bufferedStream, buffer, 1, messageLen))
                    {
                        break;
                    }
                    var message = Encoding.ASCII.GetString(buffer,1,messageLen);
                    Console.WriteLine("Message Recieved: {0}", message);

                }
        }
    }
}

这是Client.cs

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


namespace ucSim2
{
    class Program
    {
        private static byte[] msg2ByteArray(string message, Encoding enc)
        {
            var byteCount = enc.GetByteCount(message);
            if (byteCount > byte.MaxValue)
            {
                throw new ArgumentException("Message size is greater than 255 bytes in the provided encoding");
            }
            var byteArray = new byte[byteCount+1];
            byteArray[0] = (byte)byteCount;
            enc.GetBytes(message,0,message.Length,byteArray,1);
            return byteArray;
        }


        static void Main(string[] args)
        {
            String message;
            using (var tcpClient = new TcpClient())
            {
                tcpClient.Connect("127.0.0.1", 81);
                using (var networkStream = tcpClient.GetStream())
                using (var bufferedStream = new BufferedStream(networkStream))
                {
                    while (true)
                    {
                        byte[] buffer = new byte[256];
                        Console.WriteLine("Write Message");
                        message = Console.ReadLine();
                        var byteArray = msg2ByteArray(message, Encoding.ASCII);
                        bufferedStream.Write(byteArray, 0, byteArray.Length);
                    }

                }
            }
        }
    }
}

我在发布问题后就想通了...应该花更多时间才开始行动并发布问题...抱歉

最佳答案

发送消息后,您应该调用Flush() method :

bufferedStream.Write(byteArray, 0, byteArray.Length); 
bufferedStream.Flush(); // add this line

关于c# - C# 中的简单客户端服务器应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18011923/

相关文章:

c# - 在 Visual Studio 2012 中移动 obj 文件夹

c++ - QUdpSocket 不发出 readyRead() 信号

c getaddrinfo 没有这样的主机是已知的

c# - 使用 MediaElement 播放路径中带有#的网络驱动器文件

c# - Linq中有没有一种方法可以根据不同的条件应用不同的计算

c# - RelayCommand<T> 上的 CanExecute 不起作用

c# - PropertyInfo 上的 GetSetMethod 和 SetMethod 有什么区别?

asp.net - Visual Studio 2019 中多个帐户的 DefaultAzureCredential 异常

c# - 在使用 C# 的 Visual Studio 2008 中,如何设置属性监视?

java - 聊天客户端一次只打印一行