修改 利用NetworkCommsDotNet提供的所有强大功能,看起来这个库不再受到支持了。我正在改变方向,接受Eser的回答作为回答。我测试了提供的代码并且它有效。谢谢你的帮助。
下面是我的简单TCP客户端服务器代码,基于NetworkCommsDotNet库。客户端定期发送"对象"的更改位置。到服务器,服务器显示它们。这很好,但是,我想要实现的正好相反:我希望客户端只连接到服务器,一旦服务器检测到连接,它就会开始定期将一些X和Y坐标发送回客户端。我无法通过NetworkCommsDotNet完成任务,感谢任何帮助。
客户端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NetworkCommsDotNet;
using NetworkCommsDotNet.Connections.TCP;
namespace ObjectPositionClient
{
class Program
{
static void Main(string[] args)
{
try {
var conn = TCPConnection.GetConnection(new ConnectionInfo("127.0.0.1", 50747));
System.Timers.Timer tmer;
tmer = new System.Timers.Timer(3000);
tmer.Elapsed += (sender, e) => TimerElapsed(sender, e, conn);
tmer.Enabled = true;
Console.WriteLine("Press any key to exit client.");
Console.ReadKey(true);
NetworkComms.Shutdown();
}
catch (Exception e)
{
Console.WriteLine(e.InnerException + "\n" + e.Message);
}
}
static public void TimerElapsed(object sender, System.Timers.ElapsedEventArgs e, TCPConnection conn)
{
Random rnd = new Random();
int X = rnd.Next(1, 101);
int Y = rnd.Next(1, 51);
conn.SendObject("Message", "X=" + X + "; Y=" + Y);
}
}
}
服务器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NetworkCommsDotNet;
using NetworkCommsDotNet.Connections;
namespace ObjectPositionServer
{
class Program
{
static void Main(string[] args)
{
try
{
var con = Connection.StartListening(ConnectionType.TCP, new System.Net.IPEndPoint(System.Net.IPAddress.Any, 50747));
NetworkComms.AppendGlobalIncomingPacketHandler<string>("Message", PrintIncomingMessage);
Console.WriteLine("Server ready. Press any key to shutdown.");
Console.ReadKey(true);
NetworkComms.Shutdown();
}
catch (Exception e)
{
Console.WriteLine(e.InnerException + "\n" + e.Message);
}
}
private static void PrintIncomingMessage(PacketHeader header, Connection
connection, string message)
{
Console.WriteLine(message + "\n");
}
}
}
答案 0 :(得分:1)
这是基于TCP的基本客户端/服务器示例。每当客户端连接到服务器时,服务器就会向客户端发送10个字符串,然后关闭连接。我认为这与你的情况类似。
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
public class TCPTest
{
public static void StartAll()
{
Task.Run(() => StartServer());
Task.Run(() => StartClient());
}
static void StartServer()
{
TcpListener listener = new TcpListener(IPAddress.Any, 12345);
listener.Start();
Console.WriteLine("Server Started");
while (true)
{
var client = listener.AcceptTcpClient();
Console.WriteLine("A new client is connected");
ThreadPool.QueueUserWorkItem(ServerTask,client);
}
}
static void ServerTask(object o)
{
using (var tcpClient = (TcpClient)o)
{
var stream = tcpClient.GetStream();
var writer = new StreamWriter(stream);
for (int i = 0; i < 10; i++)
{
writer.WriteLine($"packet #{i + 1}");
writer.Flush();
Thread.Sleep(1000);
}
Console.WriteLine("Server session ended..");
}
}
static void StartClient()
{
TcpClient client = new TcpClient();
client.Connect("localhost", 12345);
var stream = client.GetStream();
var reader = new StreamReader(stream);
string line = "";
while((line = reader.ReadLine()) != null)
{
Console.WriteLine("Client received: "+ line);
}
Console.WriteLine("Client detected end of the session");
}
}
使用TCPTest.StartAll();
开始测试。
您甚至可以 telnet 到此服务器。 telnet localhost 12345
修改强>
由于您已注释,您希望在客户端和服务器之间传输对象,我修改为代码以显示如何完成(使用Json.Net)。这次,服务器向客户端发送10个用户对象。
我会将其作为新代码发布,以防有人想看到细微差别。
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
public class TCPTest
{
//Sample class to transfer between server and client
public class User
{
public string Name { get; set; }
public int Id { get; set; }
public DateTime BirthDate { set; get; }
}
public static void StartAll()
{
Task.Run(() => StartServer());
Task.Run(() => StartClient());
}
static void StartServer()
{
TcpListener listener = new TcpListener(IPAddress.Any, 12345);
listener.Start();
Console.WriteLine("Server Started");
while (true)
{
var client = listener.AcceptTcpClient();
Console.WriteLine("A new client is connected");
ThreadPool.QueueUserWorkItem(ServerTask, client);
}
}
static void ServerTask(object o)
{
using (var tcpClient = (TcpClient)o)
{
var stream = tcpClient.GetStream();
var writer = new StreamWriter(stream);
for (int i = 0; i < 10; i++)
{
var user = new User() { Name = $"Joe{i}", Id = i , BirthDate = DateTime.Now.AddDays(-10000)};
var json = JsonConvert.SerializeObject(user);
writer.WriteLine(json);
writer.Flush();
Thread.Sleep(1000);
}
Console.WriteLine("Server session ended..");
}
}
static void StartClient()
{
TcpClient client = new TcpClient();
client.Connect("localhost", 12345);
var stream = client.GetStream();
var reader = new StreamReader(stream);
string json = "";
while ((json = reader.ReadLine()) != null)
{
var user = JsonConvert.DeserializeObject<User>(json);
Console.WriteLine($"Client received: Name={user.Name} Id={user.Id} BirthDate={user.BirthDate}");
}
Console.WriteLine("Client detected end of the session");
}
}