c# - 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();
}
}
}
解决方案
在.Net中有几种实现实时应用程序的方法,例如:
1. SignalR
(尽可能使用 WebSockets)
2. Grpc
(它使用 http/2 和 Streaming )
MeesageBrokers
3.您也可以使用该实现pub-sub
(发布-订阅)模式构建应用程序,例如(Redis
或kafka
或..)
推荐阅读
- angular - Angular 11:对 HttpClient.get() 上的 UnitTest Spy 进行错误的类型检查
- javascript - 升级的 botbuilder 在部署到 azure 时不起作用
- zsh - 采购别名可防止显示较少的缓冲区
- javascript - DOMDocument() PHP 中 nodeValue 和 saveHTML() 的问题
- python-3.x - 将列表字典转换为特定格式的数据框
- android - 从共享意图过滤器启动的活动在 onNewIntent 期间不遵守 android:taskAffinity 规则
- reactjs - 在 React Native 应用程序中实现闪屏的简单方法
- java - Java 线程池服务器:我只能读取请求或成功发送响应,但不能同时读取
- reactjs - 在反应中使用枚举中的图像问题
- javascript - 如果 vuejs 将 2 个条件合二为一