在以下项目中,消息仅通过客户端发送到服务器。我需要每次客户端向服务器发送消息时,服务器程序使用 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();
}
}
}