internal class Program { public static IConnection Client; ClientName; Main(string[] args) { var host = IPAddress.Loopback; var port = 9991; var connectionFactory = new ClientBootstrap() .SetTransport(TransportType.Tcp).Build(); //New一个Client Client = connectionFactory.NewConnection(Node.Empty(), NodeBuilder.BuildNode().Host(host).WithPort(port)); Client.OnConnection += (address, connection) => { Console.WriteLine(); connection.BeginReceive(Received); }; Client.OnDisconnection += (address, reason) => Console.WriteLine(); Console.WriteLine(); ClientName = Console.ReadLine(); Console.Title = , ClientName); //建立连接 Client.Open(); //加入聊天组 Join(); //等待输入 WaitInput(); } WaitInput() { while (true) { var input = Console.ReadLine(); if (!string.IsNullOrEmpty(input)) { var message = MakeSendMessage(input); SendMessage(Client, message); } } } Jion chat group Join() { var message = MakeJoinMessage(); SendMessage(Client,message); } 处理接受到的消息 Received(NetworkData data, IConnection responseChannel) { var message = MessageConverter.ToMessage(data); if (message.Command == Command.Send) { Console.WriteLine(message.Content); } } 构造聊天消息 Message MakeSendMessage(string input) { return new Message { Command = Command.Send, Content = , ClientName, input) }; } 构造加入组的消息 Message MakeJoinMessage() { var message = new Message(); message.Command = Command.Join; message.Content = ClientName; return message; } SendMessage(IConnection connection, Message message) { var messageBytes = MessageConverter.ToBytes(message); connection.Send(new NetworkData { Buffer = messageBytes, Length = messageBytes.Length }); } }
4.运行结果这样一个简单的聊天室程序就完成了。
四:Helios 2.0helios 1.0的异步编程模型是基于APM的,从helios 2.0开始会改成SocketAsyncEventArgs方式来实现异步。SocketAsyncEventArgs底层封装了IOCP,IOCP是Windows server上Socket通讯性能最高的技术,使用了IOCP的helios 2.0势必具有更高的性能,所以对于helios 2.0还是非常期待的。
示例下载: