首页 > 解决方案 > NetworkCommsDotNet 一键双向聊天

问题描述

在以下项目中,消息仅通过客户端发送到服务器。我需要每次客户端向服务器发送消息时,服务器程序使用 Console.ReadLine() 函数响应客户端,而不创建新连接并使用已经创建的相同连接;

例如,当客户端打招呼时,请稍候,否则服务器会说 answer!

当然,经过搜索,我意识到我可能应该使用connection.SendObject(),但是我不能正确使用它:((当然,如果这个答案是正确的!)

谢谢您的帮助

服务器 :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetworkCommsDotNet;
using NetworkCommsDotNet.Connections;
using System.Reflection;

namespace server
{
    class Program
    {
        static void Main(string[] args)
        {
            NetworkComms.AppendGlobalIncomingPacketHandler<string>("Message", PrintIncomingMessage);
            Connection.StartListening(ConnectionType.TCP, new System.Net.IPEndPoint(System.Net.IPAddress.Any, 1000));

            Console.WriteLine("Server listening on:\n");
            foreach (System.Net.IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP))
                Console.WriteLine("{0}:{1}", localEndPoint.Address, localEndPoint.Port);
            Console.WriteLine("\nPress any key to close server.");
            Console.ReadKey(true);
            NetworkComms.Shutdown();
        }

        /// <summary>
        /// Writes the provided message to the console window
        /// </summary>
        /// <param name="header">The packet header associated with the incoming message</param>
        /// <param name="connection">The connection used by the incoming message</param>
        /// <param name="message">The message to be printed to the console</param>
        private static void PrintIncomingMessage(PacketHeader header, Connection connection, string message)
        {
            Console.WriteLine(message);

        }

    }
}

客户 :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetworkCommsDotNet;

namespace client
{
    class Program
    {
        static void Main(string[] args)
        {
            int loopCounter = 1;
            while (true)
            {
                string messageToSend = Console.ReadLine();
                NetworkComms.SendObject("Message", "192.168.1.1", 1000, messageToSend);
                if (Console.ReadKey(true).Key == ConsoleKey.Q)
                    break;
                else loopCounter++;
            }
            NetworkComms.Shutdown();
        }
    }
}

标签: c#tcpconnectionchatnetworkcomms.net

解决方案


在.Net中有几种实现实时应用程序的方法,例如:

1. SignalR(尽可能使用 WebSockets)

2. Grpc(它使用 http/2 和 Streaming )

MeesageBrokers3.您也可以使用该实现pub-sub(发布-订阅)模式构建应用程序,例如(Rediskafka或..)


推荐阅读