技术开发 频道

一步一步实现.NET下的Socket通信编程

       【IT168 技术文档】

  随着Web技术的发展,Socket通信逐渐被人们遗忘。然而最近Socket应用却又越来越多。尤其是中国移动,中国联通的短信网关就是基于Socket通迅,另外随着大家对MSN、QQ等IM工具通迅协议的研究。协议内容也随处都可以找到。想要制作自己的MSN、QQ客户端的用户也大有人在。但习惯了WEB开发和简单UI开发的程序员却在这些协议面前迷糊了。
 
  .NET的System.Net.Sockets命名空间封装了大量Socket类。使用此命名空间可以通过简单的方法进行复杂的Sockets连接、通迅。下面我就一步步教大家建立一个基于System.Net.Sockets的通用类库,并基于此举几个例子说明如何使用这个类库。
 
  1、 首先建立一个类库项目。项目命名为 SocketLibrary,并删除自动生成的Class1.cs
 
  2、 在SocketLibrary中添加类:SocketFactory.cs
 
  3、 在默认解决方案中增加一个Windows项目SocketServerTest用于测试服务器端,并添加对SocketLibrary的引用,将此项目设为启动项目。

  4、 在SocketLibrary项目中新建类Connection。表示一个连接,增加两个属性NetWorkStream和ConnectionName。分别表示一个连接的名字和它包含的NetWorkStream。源代码如下:

using System; using System.Net; using System.Net.Sockets; namespace SocketLibrary { public class Connection { public NetworkStream NetworkStream { get{return _networkStream;} set{_networkStream = value;} } private NetworkStream _networkStream; public string ConnectionName { get{return _connectionName;} set{_connectionName = value;} } private string _connectionName; public Connection(NetworkStream networkStream,string connectionName) { this._networkStream = networkStream; this._connectionName = connectionName; } public Connection(NetworkStream networkStream): this(networkStream,string.Empty) { } } }
  5、 新建一个继承自CollectionBase的类ConnectionCollection。用于保存Connection集合。
using System; namespace SocketLibrary { public class ConnectionCollection:System.Collections.CollectionBase { public ConnectionCollection() {} public void Add(Connection value) { List.Add(value); } public Connection this[int index] { get { return List[index] as Connection; } set{ List[index] = value; } } public Connection this[string connectionName] { get { foreach(Connection connection in List) { if(connection.ConnectionName == connectionName) return connection; } return null; } } } }
  6、 新建一个类,名字为Server,用于侦听网络连接。
using System; using System.net; using System.Net.Sockets; namespace SocketLibrary { public class Server { public ConnectionCollection Connections { get{return _connections;} set{_connections = value;} } private ConnectionCollection _connections; private TcpListener _listener; public Server(TcpListener listener) { this._connections = new ConnectionCollection(); this._listener = listener; } public void Start() { while(true) { if(_listener.Pending()) { TcpClient client = _listener.AcceptTcpClient(); NetworkStream stream = client.GetStream(); this._connections.Add(new Connection(stream)); } } } } }
  7、 在SocketFactory中声明一个私有变量:System.Threading.Thread _serverListenThread;

  8、 在SocketFactory类中加入StartServer方法。当执行此方法时,初始化_ serverListenThread并在此线程中开始侦听网络连接。
public void StartServer(int port) { TcpListener listener = new TcpListener(IPAddress.Any, port); listener.Start(); Server server = new Server(listener); _serverListenThread = new System.Threading.Thread (new System.Threading.ThreadStart(server.Start)); _serverListenThread.Start(); }

 

 

0
相关文章